我正在使用角,并试图返回订阅,我知道这是不允许的。我想知道还有什么解决方案吗?
我有一个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
}
发布于 2019-12-19 09:15:21
解决这一问题的一个快速方法是:
在您的服务类中,我将返回一个可观察的(Observable<boolean>
),并使用映射格式化数据以返回布尔值:codes.length == 0
是true
或false
,不需要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
}
})
发布于 2019-12-19 08:56:48
正如高兰所说,你可以使用forkJoin。从学习rxjs
为什么使用forkJoin?当您有一组可观测值并且只关心每个操作符的最终发出值时,这个操作符最好使用。这方面的一个常见用例是,如果您希望在页面加载(或其他一些事件)上发出多个请求,并且只希望在收到所有人的响应时才采取行动。通过这种方式,它类似于您使用Promise.all的方式。
示例可以在https://www.learnrxjs.io/operators/combination/forkjoin.html上创建
https://stackoverflow.com/questions/59413740
复制相似问题