我在我的应用程序中有四个HTTP调用(在单击按钮之后),其中第四个调用依赖于上述三个调用。我希望第四个调用等待并从所有三个调用中获取数据。(我从三次调用中获得的数据需要作为输入发送到第四次调用)
LoadDetails() {
this.DataService.M1().subscribe((Model1: Project.Models.Model1[]) => {
this.SomeData1 = Model1;
});
this.DataService.M2().subscribe((Model2: Project.Models.Model2[]) => {
this.SomeData2 = Model2;
});
this.DataService.M3().subscribe((Model3: Project.Models.Model3[]) => {
this.SomeData3 = Model3;
});
this.DataService.M4(this.SomeData1.Id, this.SomeData2.Id, this.SomeData3.Id).subscribe((Model4: Project.Models.Model4[]) => {
this.SomeData4 = Model4;
});
}
如何让第四个呼叫等待上述三个呼叫完成?
发布于 2017-02-27 20:37:44
这应该能帮到你:
LoadDetails() {
Observable.forkJoin([this.DataService.M1(), this.DataService.M2(), this.DataService.M3()]).mergeMap((datas:any[]) => {
this.SomeData1 = data[0];
this.SomeData2 = data[1];
this.SomeData3 = data[2];
//Here you can do whatever you want, bevor you request SomeData4
return this.DataService.M4(this.SomeData1.Id, this.SomeData2.Id, this.SomeData3.Id);
}).subscribe((Model4: Project.Models.Model4[]) => {
this.SomeData4 = Model4;
});
}
这将同时请求SomeData1-3
,如果所有数据都存在,它将请求SomeDate4
;
注意:
如果不加载所有RxJS运算符,则必须添加以下导入:
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/forkJoin';
发布于 2017-02-27 21:33:43
您可以使用区域概念来处理此类操作。Zone.js
let LoadDetailsZone = Zone.current.fork({
name: 'detailZone',
onHasTask() {
this.DataService.M4(this.SomeData1.Id, this.SomeData2.Id, this.SomeData3.Id).subscribe((Model4: Project.Models.Model4[]) => {
this.SomeData4 = Model4;
});
}
})
LoadDetailsZone.run(() => {
this.DataService.M1().subscribe((Model1: Project.Models.Model1[]) => {
this.SomeData1 = Model1;
});
this.DataService.M2().subscribe((Model2: Project.Models.Model2[]) => {
this.SomeData2 = Model2;
});
this.DataService.M3().subscribe((Model3: Project.Models.Model3[]) => {
this.SomeData3 = Model3;
});
})
您可以使用onHasTask
函数定义一个区域,该函数在zone.run()中的所有调用之后调用。
发布于 2017-02-27 20:26:31
this._villageService.GetAllVillages()
.flatMap(
(response) => {
// take from the response what you want and use it for the next call
this._villageService.GetAllWorkAreas(//pass the thing from your previous response here)
}
)
.flatMap(
....
)
.subscribe(...)
https://stackoverflow.com/questions/42485769
复制相似问题