![](/img/trans.png)
[英]Angular wait for multiple http requests to complete and then fire the last one
[英]Angular wait for multiple http requests to complete
我有一個與這篇文章非常相似的問題: Angular wait for multiple http requests to complete 然后觸發最后一個
我想實現這樣的字面意思:
forkJoin(
this.data.getCodes('medical'),
this.data.getCodes('delay'),
this.data.getCodes('disability'),
this.data.getCodes('district'),
).subscribe(([medicalData, delayData, disabilityData, districtData]) => {
this.Medical = medicalData;
this.Delays = delayData;
this.Disability = disabilityData;
this.District = districtData;
// make your last http request here.
});
除了我不知道我會提出多少 http 請求之外。 我的輸入將是一個 url 數組,api 會為每個調用返回一個字符 object,我會存儲它們。 但我不知道我會傳遞多少個 url,可能是 10,也可能是 0,具體取決於數組的長度
使用forkJoin
時,數組的長度無關緊要。 在動態長度的情況下,您可以將來自forkJoin
的響應分配給單個變量,而不是使用如圖所示的擴展語法。
此外,您應該使用更高階的映射運算符,例如switchMap
到 map 到另一個可觀察對象而不是嵌套訂閱。
urlArray = [
this.http.get('url1'),
this.http.get('url2'),
this.http.get('url3'),
this.http.get('url4'),
...
];
forkJoin(urlArray).pipe(
switchMap((res: any) =>
this.http.get('finalUrl').pipe(
map((final: any) => ([res, final])) // <-- do this if you need response from `forkJoin`
);
)
).subscribe({
next: ([resArr, resFinal]) => {
// resArr - [
// response from this.http.get('url1'),
// response from this.http.get('url2'),
// response from this.http.get('url3'),
// ...
// ];
// resFinal - response from this.http.get('finalUrl')
},
error: (error: any) => {
// handle error
}
);
ForkJoin 實際上接受一個 observables 參數數組,所以你可以做這樣的事情。
const arr = [this.data.getCodes('medical'), this.data.getCodes('delay')];
//add more observables to your arrays
arr.push(this.data.getCodes('disability'));
//use spread operator on subscribe response
forkJoin(arr).subscribe(([...arrayResp])=>{
//arrayResp will contain array of response
let theFirstResponse = arrayResp[0];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.