使用Observables/RxJS在Angular中合并两个相关的API调用 [英] Merge Two Dependent API Calls in Angular with Observables/RxJS

查看:40
本文介绍了使用Observables/RxJS在Angular中合并两个相关的API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个返回JSON的API调用:

Say I have two API calls that return JSON:

行:

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

rowDetails:

rowDetails:

{
  details: { this row details } 
}

我需要获取行,然后遍历每个行对象,并获取detailId来再次调用rowDetails,然后将详细信息附加到该行对象.最终的结构需要像这样发出:

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

在角度1中,我将使用q.allSettled等待所有调用结束.

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.

我已经尝试过了:

 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仅发出rowDetails调用.在合并最终产品的结果时,如何遍历row调用中的每个对象,并将该detailId用作另一个调用?任何帮助将不胜感激.

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.

推荐答案

您需要获取每个项目,创建一个HTTP请求,并在此内部请求完成后再传播更新的项目.

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

请注意,我实际上是从内部 map 返回 group .显然有很多方法可以解决此问题,但我认为这是最简单的方法.

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.

这篇关于使用Observables/RxJS在Angular中合并两个相关的API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆