从角度8并行处理多个API请求



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

例如,我有一个请求数组arr1[请求1、请求2、请求3、请求4],每个请求需要不同的时间才能得到响应。因此,我需要根据响应执行不同的操作,如actn1、actn2、actn3等。我需要以FCFS方式调用每个操作。有些请求会比其他请求更快地完成执行,所以每当我得到每个请求的响应时,我都需要调用相应的操作,最后在得到所有响应后,我也需要调用finalAction。

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

尝试使用combineLatest(),确保每个可观察到的值至少发出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()来迭代可观察的

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

我从@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

最新更新