Javascript 如何将两个 observable 的结果合并为 angular?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45518285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:04:54  来源:igfitidea点击:

How to combine the results of two observable in angular?

javascriptangular

提问by niaomingjian

How to combine the results of two observable in angular?

如何将两个 observable 的结果合并为 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;
}

The above is wrong, because we couldn't get data1 and data2 immediately.

以上是错误的,因为我们无法立即获取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;
}

I can combine the results in the subscribe method of the second observable. But I'm not sure if it's a good practice to achieve my requirement.

我可以在第二个 observable 的 subscribe 方法中合并结果。但我不确定这是否是实现我的要求的好习惯。

Update:
Another way I found is using forkJointo combine the results and return a new observable.

更新
我发现的另一种方法是使用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(){
  // 
}

回答by Graham

A great way to do this is to use the rxjs forkjoin operator (which is included with Angular btw), this keeps you away from nested async function hell where you have to nest function after function using the callbacks.

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

Here's a great tutorial on how to use forkjoin (and more):

这是一个关于如何使用 forkjoin(以及更多)的很棒的教程:

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

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

In the example you make two http requests and then in the subscribe fat arrow function the response is an array of the results that you can then bring together as you see fit:

在示例中,您发出两个 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];
});

The first element in the array always corresponds to the first http request you pass in, and so on. I used this successfully a few days ago with four simultaneous requests and it worked perfectly.

数组中的第一个元素始终对应于您传入的第一个 http 请求,依此类推。几天前我成功地使用了它,同时有四个请求,它工作得很好。

回答by Sandeep Kumar

We can combine observables in different ways based on our need. I had two problems:

我们可以根据需要以不同的方式组合 observables。我有两个问题:

  1. The response of first is the input for the second one: flatMap() is suitable in this case.
  2. Both must finish before proceeding further: forkJoin()/megre()/concat() can be used depending on how you want your output.
  1. 第一个的响应是第二个的输入: flatMap() 适合这种情况。
  2. 两者都必须在继续之前完成:可以根据您想要的输出方式使用 forkJoin()/megre()/concat()。

You can find details of all the above functions here. You can find even more operations that can be performed to combine observables here.

您可以在此处找到上述所有功能的详细信息。您可以在此处找到更多可用于组合 observable 的操作。