How to send Multiple Http request sequentially in Angular

心不动则不痛 提交于 2020-01-25 10:10:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!