0

I'm trying to return an Observable of object(s), depending on an other service call, here is a simple example:

public getMyObject(): Observalbe<MyObject> {
    let myObject;
    this.isFeautreEnabled().subscribe(isEnabled=> {
        if (isEnabled) {
            myObject = this.http.get<MyObject>('domain/path'); 
        } else {
            myObject = of();
        }
    })
    return myObject;
}

So I want to return MyObject from the service, if the feature is enabled (async call also), and something else otherwise (null in this case).

This doesn't work, because isFeatureEnabled is async as well.

Note that I can't change the method signature to async, because it would change the return type as well.

1 Answer 1

1

Use switchMap operator.

public getMyObject(): Observalbe<MyObject> {
    return this.isFeautreEnabled().pipe(
      switchMap(isEnabled => isEnabled ? this.http.get<MyObject>('domain/path') : of()),
    );
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.