Merge Two Dependent API Calls in Angular with Observables/RxJS

别等时光非礼了梦想. 提交于 2021-02-08 05:10:29

问题


Say I have two API calls that return JSON:

rows:

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

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. 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.

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. 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? Any help would be greatly appreciated.


回答1:


You need to take each item, create an HTTP request and after this inner request completes then propagate the updated item further.

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. There are obviously many ways to approach this but I think this is the easiest one.



来源:https://stackoverflow.com/questions/43946886/merge-two-dependent-api-calls-in-angular-with-observables-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!