【发布时间】:2017-09-11 14:28:07
【问题描述】:
我在 Angular 4 中使用 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)
}
)
}
所以,我的问题是应该如何编写这段代码,以便它从服务器获取响应,但在移动到下一个平面图之前等待另一个 rest 调用也完成。
this.name = this.repoService.getDocProperties(this.objectId);
【问题讨论】:
-
可以使用forkJoin等多个请求完成coryrylan.com/blog/angular-multiple-http-requests-with-rxjs