【问题标题】:Handle multiple Http request using RxjS使用 RxjS 处理多个 Http 请求
【发布时间】:2022-01-19 16:05:43
【问题描述】:

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

【问题讨论】:

  • 如果第二次调用不依赖于第一次调用的响应,为什么必须在第一次调用响应之后进行?第一次和第二次通话不能同时进行吗?
  • 只是如果第一次调用没有响应或出现错误,那么我们不想进行第二次 api 调用。

标签: angular rxjs


【解决方案1】:

我认为您应该使用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 的常见模式

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多