如何合并两个 observable in angular 的结果?
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(){
//
}
最佳答案
执行此操作的一个好方法是使用 rxjs forkjoin 运算符(附带 Angular btw),这使您远离嵌套的异步函数 hell ,在这种情况下您必须使用回调在函数之后嵌套函数。
这是一个关于如何使用 forkjoin(以及更多)的很棒的教程:
https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs
在示例中,您发出了两个 http 请求,然后在订阅胖箭头函数中,响应是一个结果数组,您可以根据需要将这些结果组合在一起:
let character = this.http.get('https://swapi.co/api/people/1').map(res => res.json());
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1').map(res => res.json());
Observable.forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
数组中的第一个元素始终对应于您传入的第一个 http 请求,依此类推。几天前,我成功地使用了它,同时处理了四个请求,并且运行良好。
关于javascript - 如何结合 Angular 两个可观察结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518285/