问题
I have written below code to call an API each time before post request happens, First API gets called and the second one is not getting called
public post(postUrl: string, model: any): Observable<any> {
return this.validateTokenStatus().pipe(map(response => {
console.log('response', response);
// if (response) {
console.log('response2', response);
const url = `${environment.webApiUrl}/${postUrl}`;
this.spinnerService.start();
console.log('response21', response);
return this._http.post(url, model).pipe(map((res: any) => {
console.log('response11', response);
this.spinnerService.stop();
return res;
},
error => {
console.log('error');
return error;
}));
// } else {
// console.log('response3', response);
// return true;
// }
}));
}
回答1:
When you want to do multiple async operations in a sequence after each other you usually would want to use one of mergeMap, switchMap or concatMap. Something like this could work in this situation:
return this.validateTokenStatus()
.pipe(
switchMap(response => {
const url = `${environment.webApiUrl}/${postUrl}`;
this.spinnerService.start();
return this._http.post(url, model);
}),
map((res: any) => {
this.spinnerService.stop();
return res;
})
);
来源:https://stackoverflow.com/questions/55901788/how-to-send-multiple-http-request-sequentially-in-angular