Angular4如何使用flatMap链接forkJoin [英] Angular4 how to chain forkJoin with flatMap

查看:63
本文介绍了Angular4如何使用flatMap链接forkJoin的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我处于这样的情况:我需要进行5个可以并行执行的http调用,以及另外需要在这5个之后执行的http调用.

I'm in the situation where I need to make 5 http calls that can be executed in parallel + another http call that need to be executed after these five.

我在前5个中使用了forkJoin,但是我不知道如何链接flatMap(或其他函数).

I used forkJoin for the first 5, but I don't have any idea how to chain flatMap (or other function).

forkJoin(
      firstObservable,
      secondObservable,
      thirdObservable,
      ..)
      .subscribe(results => {

        this.myComposedObject = results[0];
        let secondResult = results[1];
        let thirdResult = results[2];
        [...]


        // !!! AT THIS POINT I WOULD NEED TO MAKE AN EXTRA CALL!
        // results[1] contains data I need to make the extra call


        // 
        this.myComposedObject.second = secondResult;
        this.myComposedObject.third = thirdResult;
});

我在组件内执行此操作,因此最后我将数据分配给myComposedObject.

I do this operation within a component, so at the end I assign data to myComposedObject.

推荐答案

就像您说的要发出5个并行请求一样,您可以使用 forkJoin .然后,您要在前5个完成时再提出一个请求,以便将其与 concatMap 运算符链接起来(或在这里也可以使用 mergeMap ).

Like you said to make 5 parallel requests you can use forkJoin. Then you want to make another request when the previous 5 complete so you'll chain it with the concatMap operator (or mergeMap would work here as well).

然后,您需要将所有结果组合在一起,以便可以使用 map 将最后一个结果添加到与前五个结果相同的数组中.

Then you need to work with all the results combined so you can use map to add the last result to the the same array as the previous five.

forkJoin(
    firstObservable,
    secondObservable,
    thirdObservable,
    ...
  )
  .concatMap(firstFiveResults => makeAnotherCall(firstFiveResults[1])
    .map(anotherResult => [...firstFiveResults, anotherResult])
  )
  .subscribe(allResults => {
    this.myComposedObject.second = allResults[1];
    this.myComposedObject.third = allResults[2];
    // allResults[5] - response from `makeAnotherCall`
    ....
  });

这篇关于Angular4如何使用flatMap链接forkJoin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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