Juluri Vinay
Juluri Vinay

Reputation: 105

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

Upvotes: 2

Views: 6063

Answers (1)

SnorreDan
SnorreDan

Reputation: 2890

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

Upvotes: 2

Related Questions