如何結合兩個觀察角度的結果?如何結合兩個觀察角度的結果?
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;
}
以上是錯誤的,因爲我們無法立即得到數據1和數據2。
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
結合的結果,並返回一個新的觀測。
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(){
//
}
你的更新應該真正的【答案】(https://stackoverflow.com/help/self-answer)。 – cartant