我在使用Angular 4中的RxJS編寫異步調用。RxJS - 解決多個服務器調用
我需要調用服務器,得到響應,並用它來撥打另一個電話,得到這樣的迴應,並用它來撥打另一個電話等。我正在使用下面的代碼爲此,並按預期工作
id;
name;
ngOnInit() {
this.route.params
.flatMap(
(params: Params) => {
this.id = params['id'];
return this.myService.get('http://someurlhere');
}
)
.flatMap(
(response: Response) => {
return this.myService.get('http://someurlhere');
})
.flatMap(
(response: Response) => {
return this.myService.get('http://someurlhere');
})
.subscribe(
(response: Response) => {
FileSaver.saveAs(blob, this.name);
},
(error) => {
console.log('Error ' + error)
}
)
}
現在,我需要做一些更改。在第一個flatMap中,我需要進行2次其餘呼叫,並且只有在兩個呼叫都被解析後才能繼續。這不僅只是其中之一的響應將被傳遞到下一個flatMap,因爲其他呼叫只會填充一個變量
id;
name;
ngOnInit() {
this.route.params
.flatMap(
(params: Params) => {
this.id = params['id'];
// this is the 2nd REST call. It just populates a variable, so don't need the output to be passed to next flatMap. However, both the URLs in this section should resolve before the next flatMap is executed.
this.name = this.myService.get('http://someotherurlhere');
return this.myService.get('http://someurlhere');
}
)
.flatMap(
(response: Response) => {
return this.myService.get('http://someurlhere');
})
.flatMap(
(response: Response) => {
return this.myService.get('http://someurlhere');
})
.subscribe(
(response: Response) => {
FileSaver.saveAs(blob, this.name);
},
(error) => {
console.log('Error ' + error)
}
)
}
所以,我的問題是,應該如何這段代碼被寫入使它從服務器獲取響應,但在移動到下一個平面映射之前,等待另一個其他呼叫也完成。
this.name = this.repoService.getDocProperties(this.objectId);
您可以使用forkJoin等到多個請求完成https://coryrylan.com/blog/angular-multiple-http-requests- with-rxjs –