【发布时间】:2017-08-05 04:43:14
【问题描述】:
如何在angular中合并两个observable的结果?
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;
}
我可以在第二个 observable 的 subscribe 方法中组合结果。 但我不确定这是否是实现我的要求的好习惯。
更新:
我发现的另一种方法是使用 forkJoin 组合结果并返回一个新的 observable。
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(){
//
}
【问题讨论】:
-
你的更新应该是answer。
-
一些像
route.url(路由:ActivatedRoute)这样的observables没有完成,在这种情况下:stackoverflow.com/questions/45172111/…
标签: javascript angular