简体   繁体   中英

Angular Return Observable from subscription

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.

Use switchMap operator.

public getMyObject(): Observalbe<MyObject> {
    return this.isFeautreEnabled().pipe(
      switchMap(isEnabled => isEnabled ? this.http.get<MyObject>('domain/path') : of()),
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM