我想找一个给定团队的工作项目。这需要分两步进行:
这就是我获得工作清单的方式:
WorklistService.ts
public getByTeamId(teamId): Observable<Worklist> {
return this._http
.get(url + "/" + teamId)
.map(res => res.json().data as Worklist)
.catch(this.handleError);
}
以下是我获取附加到该列表的工作项的方法:
WorkItemService.ts
public getByWorklistId(worklistId): Observable<WorkItem[]> {
return this._http
.get(url + "/" + worklistId)
.map(res => res.json().data as WorkItem[])
.catch(this.handleError);
}
然后在我的组件中,我需要以某种方式链接这些调用。这就是我到目前为止所拥有的:
this._worklistService
.getByTeamId(teamId)
.subscribe(
worklist => {
if (worklist) {
this._workItemService
.getByWorklistId(worklist._id)
.subscribe(
workItems => this.workItems = workItems,
error => console.log("Could not retrieve work items"));
}
},
error => console.log("Could not retrieve worklist"));
这真的是连接这些电话的最佳方式还是有更优雅的方式?
答案 0 :(得分:1)
您可以利用flatMap
运算符来执行此操作:
this._worklistService
.getByTeamId(teamId)
.flatMap(
worklist => {
if (worklist) {
return this._workItemService
.getByWorklistId(worklist._id);
} else {
return Observable.throw('worklist is undefined');
}
})
.subscribe(
workItems => this.workItems = workItems,
error => console.log("Could not retrieve work items"));
当第一个请求完成异步数据流时,此运算符允许插入另一个请求。