我在角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中,我需要进行两个rest调用,只有当这两个调用都得到解决时才继续进行。不仅如此,其中之一的响应将传递到下一个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);
发布于 2017-09-11 06:37:13
您可以将异步调用与forkJoin结合起来。
在您的情况下,您有两个电话:
this.myService.get('http://someotherurlhere');
this.myService.get('http://someurlhere');
它们可以这样组合在一起:
let call1 = this.myService.get('http://someotherurlhere');
let call2 = this.myService.get('http://someurlhere');
return Observable.forkJoin([call1, call2])
当您订阅(或链接其他函数)到可观察的连接时,返回的数据将位于数组中。因此,call1
的结果将位于索引0,而call2
将位于索引1。
Observable.forkJoin([call1, call2]).subscribe((results) => {
results[0]; // call1
results[1]; // call2
});
https://stackoverflow.com/questions/46158118
复制