简体   繁体   English

使用Observables / RxJS在Angular中合并两个相关的API调用

[英]Merge Two Dependent API Calls in Angular with Observables/RxJS

Say I have two API calls that return JSON: 假设我有两个返回JSON的API调用:

rows: 行:

{
  {"row": 1, detailId: "a"}
  {"row": 2, detailId: "b"}
}

rowDetails: rowDetails:

{
  details: { this row details } 
}

I need to get rows, then loop through each row object getting the detailId to make another call to rowDetails, and attach the details to the row object. 我需要获取行,然后遍历每个行对象,并获取detailId以再次调用rowDetails,然后将详细信息附加到该行对象。 The final structure needs to be emitted like so: 需要发出最终结构,如下所示:

{
  {"row": 1, "detailId": a, "details": { row details}}
  {"row": 2, "detailId": b, "details": { row details}}
}

In angular 1 I would use q.allSettled to wait for all the calls to finish. 在角度1中,我将使用q.allSettled等待所有调用结束。

I'm trying to do this the observable way and I am struggling conceptually and practically. 我正在尝试以可观察的方式做到这一点,并且在概念上和实践上都在挣扎。 I don't get how you are supposed to actually emit a merged "stream" as the final product. 我不知道您应该如何实际发出合并的“流”作为最终产品。

I've tried roughly: 我已经尝试过:

 this.http
     .get('rows')
     .map(res => res.json())
     .flatMap(group => this.http.get('rowDetails' + detailId))
     .map(res => res.json()).
     .subscribe(res => console.log(res))

Subscribe just emits the rowDetails call. 订阅仅发出rowDetails调用。 How do I iterate through each object in the rows call and take that detailId for another call while merging the results for the final product? 在合并最终产品的结果时,如何遍历row调用中的每个对象,并将该detailId用作另一个调用? Any help would be greatly appreciated. 任何帮助将不胜感激。

You need to take each item, create an HTTP request and after this inner request completes then propagate the updated item further. 您需要获取每个项目,创建一个HTTP请求,然后在此内部请求完成之后,再传播已更新的项目。

this.http
    .get('rows')
    .map(res => res.json())
    .flatMap(group => this.http.get('rowDetails' + group.detailId)
        .map(res => {
            group.details = res.json();
            return group;
        })
    )
    .subscribe(res => console.log(res))

Notice that I'm actually returning group from the inner map . 注意,我实际上是从内部map返回group There are obviously many ways to approach this but I think this is the easiest one. 显然有很多方法可以解决此问题,但我认为这是最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM