繁体   English   中英

如何在Angular中顺序发送多个Http请求

[英]How to send Multiple Http request sequentially in Angular

我写了下面的代码,每次在发布请求发生之前调用一个API,第一个API被调用而第二个API没有被调用

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

当您要依次执行多个异步操作时,通常希望使用mergeMap,switchMap或concatMap中的一个。 在这种情况下,可能会发生以下情况:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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