简体   繁体   中英

How to send Multiple Http request sequentially in Angular

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;
        // }
    }));
}

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;
    })
  );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM