【问题标题】:Handle multiple API requests parallel from angular 8从 Angular 8 并行处理多个 API 请求
【发布时间】:2020-07-16 14:40:49
【问题描述】:

我需要从我的 Angular 应用程序并行调用多个 API 请求,并且我需要分别获取每个响应(需要为每个响应执行一些不同的操作),并且我还需要跟踪所有请求何时完成执行

例如,我有一个请求数组 arr1[request1,request2,request3,request4],每个请求将花费不同的时间来获得响应。所以我需要根据不同的操作,如 actn1、actn2、actn3..etc到响应。我需要以 FCFS 方式调用每个操作。某些请求将比其他请求更快地完成执行,因此每当我得到每个请求的响应时,我都需要调用相应的操作,最后在获得所有响应后,我还需要调用 finalAction。

通过使用 forkJoin 我能够执行我的 finalAction(在完成所有请求执行后这必须工作)但我不知道每当响应来自服务器时我将如何执行每个响应操作

【问题讨论】:

  • 尝试使用combineLatest() 确保每个可观察对象发出至少1个值:learnrxjs.io/learn-rxjs/operators/combination/combinelatest
  • 由于我是 Angular 新手,你能用这个 combineLatest() 为上述示例提供一个基本代码
  • 我已经使用tap pipeable 运算符发布了答案。
  • 好的,谢谢,我试试这个

标签: angular rxjs http-post


【解决方案1】:

尝试使用combineLatest(),它可以确保每个 observable 至少发出 1 个值。 您可以使用.pipe()tap() 对任何可观察对象采取单独的行动。

combineLatest([

   req1.pipe(tap(result => {
     /* take action */
   })),

   req2.pipe(tap(result => {
     /* take another action */
   })),

   req3.pipe(tap(result => {
     /* take a super action */
   })),

   req4.pipe(tap(result => {
     /* do nothing maybe */
   }))

]).subscribe((resultArray) => {
  /* take the final action as all of the observables emitted at least 1 value */
})

combineLatest参考:https://www.learnrxjs.io/learn-rxjs/operators/combination/combinelatest

tap参考:https://www.learnrxjs.io/learn-rxjs/operators/utility/do


更新

如果你有一个动态长度的数组,你可以在 combineLatest() 中使用 Array.map() 来迭代 observables

const requests = [req1,req2,req3,..., reqN]

combineLatest(
  requests.map(req => req.pipe(tap(res => handleResponse(res))))
).subscribe();

const handleResponse = (response) => { /*do something*/ }

这是一个正在运行的 stackblitz 项目:https://stackblitz.com/edit/rxjs-a16kbu

【讨论】:

  • 感谢您的回答,它适用于 4 个请求,但我需要将其作为动态数组。例如,该请求数组是一个动态数组,请求的数量会有所不同,所以我尝试添加所有数组中的请求并尝试在 CombineLatest 中循环,但它显示语法问题,我可以在 CombineLatest 中编写一些循环吗????
  • 更新了答案以满足您的需求并添加了 stackblitz 项目链接。
  • 让我试试这个,谢谢你的帮助
  • 这是完美的工作,再次感谢,,,我对代码做了一个小的改动,我只是添加了下来
  • 谢谢,在 Angular8 上完美运行。另外,感谢您的更新,这是我正在使用的版本。
【解决方案2】:

我从@Harun Yilmaz 的帖子中得到了解决方案,我只是在这里添加它以供其他人参考。

getDataFromApi(url) {
    let httpOptions={};
    let param=["CAL3","CAL2","CAL1"];//dynamic parameter(CAL1:8sec,CAL2:5s,CAL3:12s)
    let httpArray=[];
for(let i=0;i<param.length;i++){
      httpArray.push(this.http.post<any>(url + `/PostDataSet?Id=${param[i]}`, {}, httpOptions))
   }
   const handleResponse = (response) => {
       //here i am getting each response in a first come first manner
       console.log(response.Table[0].Output);
      }
const combineResponse =combineLatest(
  httpArray.map(req => req.pipe(tap(handleResponse)))
   )
    return combineResponse;
}
//output
 CAL2
 CAL1
 CAL3

【讨论】:

  • 您可以简化数组创建,例如:let httpArray = param.map(p =&gt; this.http.post&lt;any&gt;( `${url}/PostDataSet?Id=${p}`, {}, httpOptions))
猜你喜欢
  • 2023-01-30
  • 2021-05-26
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 2013-06-12
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多