如何结合角度的两个可观察结果?
this.http.get(url1)
.map((res: Response) => res.json())
.subscribe((data1: any) => {
this.data1 = data1;
});
this.http.get(url2)
.map((res: Response) => res.json())
.subscribe((data2: any) => {
this.data2 = data2;
});
toDisplay(){
// logic about combining this.data1 and this.data2;
}
上面是错误的,因为我们不能马上得到data1和data2。
this.http.get(url1)
.map((res: Response) => res.json())
.subscribe((data1: any) => {
this.http.get(url2)
.map((res: Response) => res.json())
.subscribe((data2: any) => {
this.data2 = data2;
// logic about combining this.data1 and this.data2
// and set to this.data;
this.toDisplay();
});
});
toDisplay(){
// display data
// this.data;
}
我可以将结果合并到第二个可观察对象的订阅方法中。但是我不确定实现我的要求是否是一个好习惯。
更新:
我发现的另一种方法是使用 forkJoin
组合结果并返回一个新的可观察值。
let o1: Observable<any> = this.http.get(url1)
.map((res: Response) => res.json())
let o2: Observable<any> = this.http.get(url2)
.map((res: Response) => res.json());
Observable.forkJoin(o1, o2)
.subscribe(val => { // [data1, data2]
// logic about combining data1 and data2;
toDisplay(); // display data
});
toDisplay(){
//
}
原文由 niaomingjian 发布,翻译遵循 CC BY-SA 4.0 许可协议
一个很好的方法是使用 rxjs forkjoin 运算符(它包含在 Angular btw 中),这使您远离嵌套的异步函数地狱,在那里您必须使用回调函数一个接一个地嵌套函数。
这是关于如何使用 forkjoin(以及更多)的精彩教程:
https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs
在示例中,您发出了两个 http 请求,然后在 subscribe fat arrow 函数中,响应是一个结果数组,您可以根据需要将这些结果组合在一起:
数组中的第一个元素始终对应于您传入的第一个 http 请求,依此类推。几天前,我成功地使用了它,同时处理了四个请求,并且效果很好。