订阅中返回布尔值的替代方法

时间:2019-12-19 16:38:32

标签: angular typescript rxjs

我正在使用angular并试图在我知道不允许的订阅中返回。我想知道还有什么其他解决方案可用吗?

我有一个hasChildren方法,该方法订阅一个checkChildren方法(这是API调用所在的位置)。然后在另一个类中调用此hasChildren方法,并期望该布尔值。谁能建议其他做事方式?

export class Services {

    constructor(
        protected httpClient: HttpClient,
        protected backendService: BackendService
    ) { }


    serviceCodeAppend: string;
    childrenBool: boolean;

    hasChildren(serviceCode: string): boolean{
        console.log('in hasChildren');
        this.checkChildren(serviceCode).subscribe((codes) => {
            console.log(codes)
            if (codes.length == 0) {
                this.childrenBool = false;
            } else {
                this.childrenBool = true;
            }
            return this.childrenBool;
        });
    }

    checkChildren(serviceCode: string): Observable<any> {
        console.log('function checkChildren called');
        this.serviceCodeAppend = serviceCode + "_";
        return this.httpClient.get<any>(`${this.backendService.url}/table_name?service=like.${this.serviceCodeAppend}`).pipe(
            catchError(error => {
                this.backendService.handleError(error);
                return of({});
            })
        ).pipe(shareReplay(1));
    }

}

我需要在另一类的这一行代码中使用布尔值:

if (this.service.hasChildren(selectedSectorCode)) {
   // do something
}

2 个答案:

答案 0 :(得分:1)

对此的快速解决方法是:

在您的服务类中,我将返回一个可观察的(Observable<boolean>)并使用map格式化数据以返回布尔值:codes.length == 0truefalse否需要if语句。

     hasChildren(serviceCode: string): Observable<boolean>{
        return this.checkChildren(serviceCode).pipe(map((codes) => {
            console.log(codes)
            return codes.length == 0;
        }));
    }

别忘了导入import { map } from 'rxjs/operators';

在另一堂课中,我会:

this.service.hasChildren(selectedSectorCode).subscribe((check) => {
     if (check)) {
        // do something
     }
})

答案 1 :(得分:0)

正如Gauran所说,您可以使用forkJoin。 从学习rxjs

  

为什么要使用forkJoin?当您有一组   可观察到的东西,只关心它们的最终发射值。一   常见的用例是,如果您希望发出多个请求   页面加载(或其他事件),并且只希望在   已收到所有人的答复。这样类似于   您可以使用Promise.all。

示例可以为https://www.learnrxjs.io/operators/combination/forkjoin.html