private getScmServiceMeta(serviceId: string): Observable<any> {
let service = this.getServiceItem(serviceId);
if (service) {
return this.httpClient.get(serviceUri).map((res: Response) => {
return _.get(res, 'data.serviceinfo');
})
} else {
return Observable.throw('backend server error');
}
}
public inquireScmData(serviceId: string, params: object, templateId: string): Observable<any> {
return this.getScmServiceMeta(serviceId).map((serviceInfo: any) => {
let uri = serviceInfo.routeTemplate;
// How to return the _.get(res, 'data') as an Observable ???
return this.httpClient.get(uri).map((res: Response) => {
if (_.startsWith(_.get(res, 'status.code'), '200')) {
return _.get(res, 'data');
} else {
throw ('status code error');
}
})
})
}
作为上面的代码,我需要在调用函数'inquireScmData'时返回一个observable,但是在函数内部,它需要调用另一个函数'getScmServiceMeta',这也是异步的并且还返回一个Observable,所以如何返回'_.get(res,'data')'作为Observable ??? 感谢
答案 0 :(得分:1)
rxjs
为Observable提供了一个静态方法来执行此操作。
Observable.of( _.get(res, 'data') );
但是,您将拥有Observable<Observable<Observable<any>>>
。这是你想要的,或者你只是想链接“异步”操作。如果是这样,您应该按原样保留代码,并使用mergeMap
。
public inquireScmData(serviceId: string, params: object, templateId: string): Observable<any> {
return this.getScmServiceMeta(serviceId).mergMap((serviceInfo: any) => {
let uri = serviceInfo.routeTemplate;
return this.httpClient.get(uri).map((res: Response) => {
if (_.startsWith(_.get(res, 'status.code'), '200')) {
return _.get(res, 'data');
} else {
throw ('status code error');
}
})
})
}