【问题标题】:Angular4 how to chain forkJoin with flatMapAngular4如何用flatMap链接forkJoin
【发布时间】:2018-03-15 16:51:02
【问题描述】:

我的情况是我需要进行 5 个可以并行执行的 http 调用 + 需要在这 5 个之后执行的另一个 http 调用。

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

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。

【问题讨论】:

    标签: angular http rxjs chaining


    【解决方案1】:

    就像你说的发出 5 个并行请求,你可以使用 forkJoin。然后你想在前 5 个完成后发出另一个请求,这样你就可以用 concatMap 运算符链接它(或者 mergeMap 也可以在这里工作)。

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

    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`
        ....
      });
    

    【讨论】:

      【解决方案2】:

      谢谢,这为我指明了正确的方向。 我对结果类型有一些问题。当我尝试分配时

      this.myComposedObject.second = allResults[1];
      

      编译器抱怨类型转换,所以我会在这里向其他人报告我的解决方案。

      为了摆脱这个问题,你可以利用“解构”(更多信息:https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

      forkJoin(
          firstObservable,
          secondObservable,
          thirdObservable,
          ...
        )
        .concatMap(firstFiveResults => makeAnotherCall(firstFiveResults[1])
          .map(anotherResult => [...firstFiveResults, anotherResult])
        )
        .subscribe((allResults: [
           TypeA, <-- type returned from firstObservable
           TypeB, 
           TypeC, 
           TypeD, 
           TypeE
         ]) => {
          this.myComposedObject.second = allResults[1];
          this.myComposedObject.third = allResults[2];
          // allResults[5] - response from `makeAnotherCall`
          ....
        });
      

      【讨论】:

        猜你喜欢
        • 2018-01-03
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        • 2020-04-19
        • 2019-10-24
        • 1970-01-01
        • 1970-01-01
        • 2020-04-26
        相关资源
        最近更新 更多