[英]How can I perform multiple http request in Angular 2+ but wait for each to complete before doing the next?
我有類似的東西:
// Build requests array
const requests = [];
contacts.forEach(contact => {
requests.push(
this.httpService.post('/users', { name: contact.name })
);
});
// Run them all at once and do stuff when they all complete
return Observable.forkJoin(requests).pipe(
map(() => console.log('All requests are done!')),
catchError(() => console.log('Something went wrong'))
);
像這樣使用forkJoin
可以一次發出所有http請求。 我該如何一個接一個地處理請求? 也就是說,我希望請求1完成,然后運行請求2,依此類推。我找不到執行此操作的任何rxjs運算符。
只需使用concat
。 當上一個Observable完成時,它將一個接一個地訂閱每個源Observable。
import { concat } from 'rxjs';
...
concat(...requests).pipe(
toArray(), // Collect all responses to a single array
).subscribe((results) => ...);
也許您甚至不使用toArray
,這取決於您要對響應執行的操作。
您可以將flatMap
用於此類http請求。 這是我的一段代碼,可以為您工作。
public sendMailForExit(email) {
email.employee.token = Common.newGuid();
return this.http.postRequest(StaticKeywords.url_email + 'InitialSaveEmployeeExitDetails', email).map((response: Response) => {
return response;
})
.flatMap((token: any) => {
if (token.json().success === true) {
email.employee.url = StaticKeywords.baseUrlApp + '#/' + StaticKeywords.url_employee + StaticKeywords.url_exitDetail +
email.employee.ID + '/' + email.employee.token;
return this.http.postRequest(StaticKeywords.url_email + 'sendEmail', email).map((innerResponse: Response) => {
return this.CheckResponse(innerResponse);
});
} else {
return [{ token: token }];
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.