使用 RxjS 处理多个 Http 请求

Handle multiple Http request using RxjS

我有一个场景,我想先进行 HTTP 调用,当响应 (1) 到来时,我想进行不需要响应 (1) 的第二次 HTTP 调用,并假设这是第二次 HTTP 调用给出响应(2)。现在我想进行多个 HTTP 调用,这些调用将使用来自 response(1) 和 response(2) 的数据。我如何使用 RxJS 实现此目的?

我认为你应该使用 concatMap 运算符加上一些技巧将第一次调用的响应移动到最后一次调用。

因此代码可能如下所示

firstCall().pipe(
   // use concatMap to make sure you make the second call after the first one completes
   concatMap(resp_1 => {
      return secondCall().pipe(
         // use map here to move both the first and second response down the pipeline
         map(resp_2 => {
           // here we place both responses into an object which is returned by map
           return {resp_1, resp_2}
         })
      ),
      // now it is time to make all other calls once the second call has completed
      // therefore again we use concatMap
      concatMap(({resp_1, resp_2}) => {
         // the function passed to concatMap has to return an Observable
         // I assume these calls can be made in parallel and so I use forkJoin
         // which returns an Observable which notifies as soon as all the 
         // calls have completed
         return forkJoin([thirdCall({resp_1, resp_2}), fourthCall({resp_1, resp_2}), ...])
      })
   })
)
// here you subscribe
.subscribe({
   next: arrayOfResponses => {
      // do something with the array of responses of thirdCall, fourthCall and so on
   }
})

您可能会发现 this article interesting,因为它讨论了通过 http 调用使用 RxJs 的常见模式