如何将两个可观察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;
}

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

我可以将结果合并到第二个可观测对象的Subscribe方法中. 但我不确定这是否是达到我要求的好做法.

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

推荐答案

编辑2021:以下是更新的教程:

https://scotch.io/tutorials/rxjs-operators-for-dummies-forkjoin-zip-combinelatest-withlatestfrom/amp

实现这一点的一个好方法是使用rxjs forkjoin操作符(Angular btw中包含),这使您远离嵌套的异步函数地狱,在那里您必须使用回调函数一个接一个地嵌套函数.

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

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

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

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请求,依此类推.几天前,我成功地使用了这一功能,并同时发出了四个请求,它工作得非常好.

Angular相关问答推荐

接收错误NullInjectorError:R3InjectorError(_AppModule)[config—config]....>过度安装Angular—Markdown—Editor

如何在每次Angular 编译之前执行脚本(esbuild)

第15角Cookie的单元测试用例

如何在Angular 17 SSR中处理Swiper 11 Web组件事件

HTTP POST响应失败Angular 16

如何防止打印后的空格后的HTML元素的Angular ?

崩溃Angular项目Docker容器

NG-Zorro Datepicker 手动输入掩码不起作用

为什么初始化值为 1 的BehaviorSubject 不能分配给类型number?

Aws 代码部署在 BeforeBlockTraffic 步骤失败,即使在更新策略后也会超时

如何在 cypress 测试中实现拖放?

如何在 Angular 2 模板中使用枚举

在 Angular2 中跟踪 Google Analytics 页面浏览量

找不到模块'@angular/compiler'

angular 2模板使用console.log

在 Angular 2 中打印 Html 模板

如何在 Angular 4 中翻译 mat-paginator?

如何作为模块的子模块路由到模块 - Angular 2 RC 5

如何从指令访问主机组件?

如何将 @Input 与使用 ComponentFactoryResolver 创建的组件一起使用?