2017-08-05 56 views
2

如何结合两个观察角度的结果?如何结合两个观察角度的结果?

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(){ 
    // 
} 
+1

你的更新应该真正的【答案】(https://stackoverflow.com/help/self-answer)。 – cartant

回答

2

一个伟大的方式做,这是使用forkjoin运营商rxjs(其中包括与角BTW)这使你远离嵌套的异步函数地狱,你必须在使用回调函数之后嵌套函数。

下面是关于如何使用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请求,依此类推。我几天前用四个同时请求成功地使用了它,并且它完美地工作。

0

写在第一observable如下的completion event第二个电话,

this.http.get(url1) 
    .map((res: Response) => res.json()) 
    .subscribe((data1: any) => { 

     this.data1=data1; 

    },(error=>{}),()=>{ 
     this.http.get(url2) 
      .map((res: Response) => res.json()) 
      .subscribe((data2: any) => { 
       this.data2 = data2; 
      }); 
    }); 
+0

问题出在何时何地合并结果。 – niaomingjian

+0

在第二次订阅的成功处理程序中。 – Aravind