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

新手上路,请多包涵

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

 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 许可协议

阅读 278
2 个回答

一个很好的方法是使用 rxjs forkjoin 运算符(它包含在 Angular btw 中),这使您远离嵌套的异步函数地狱,在那里您必须使用回调函数一个接一个地嵌套函数。

这是关于如何使用 forkjoin(以及更多)的精彩教程:

https://coryrylan.com/blog/angular-multiple-http-requests-with-rxjs

在示例中,您发出了两个 http 请求,然后在 subscribe fat arrow 函数中,响应是一个结果数组,您可以根据需要将这些结果组合在一起:

 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 请求,依此类推。几天前,我成功地使用了它,同时处理了四个请求,并且效果很好。

原文由 Graham 发布,翻译遵循 CC BY-SA 4.0 许可协议

尝试使用 forkJoin,如果它不起作用,那么试试 combineLatest() 它的作用 - 它在流数组完成之前将流数组中最后发出的值合并为一个值。

 Observable.combineLatest(
        this.filesServiceOberserval,
        this.filesServiceOberserval,
        this.processesServiceOberserval,
    ).subscribe(
        data => {
          this.inputs = data[0];
          this.outputs = data[1];
          this.processes = data[2];
        },
        err => console.error(err)
    );

原文由 Gajender Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题