Angular2 rxjs - switchmap catch error

大憨熊 提交于 2019-12-05 22:29:16

问题


I'd like to be able to handle any errors that error when calling this.authService.refreshToken(). Can errors be handled within the switchmap block, or how do I go about handling an error in this case?

post3(endpoint: string, body: string) : Observable<any> {
    if (this.authService.tokenRequiresRefresh()) {
      this.authService.tokenIsBeingRefreshed.next(true);
      return this.authService.refreshToken().switchMap(
        data => {
          this.authService.refreshTokenSuccessHandler(data);
          if (this.authService.loggedIn()) {
            this.authService.tokenIsBeingRefreshed.next(false);
            return this.postInternal(endpoint, body);
          } else {
            this.authService.tokenIsBeingRefreshed.next(false);
            this.router.navigate(['/sessiontimeout']);
            Observable.throw(data);
          }
        }
      );
    }
    else {
      return this.postInternal(endpoint, body);
    }
  }

回答1:


use the catchError method

this.authService.refreshToken()
  .pipe(
     switchMap(() => {...}),
     catchError((e) => {
       // handle e and return a safe value or re-throw
       if (isCritical(e)) {
         return throwError(e);
       }
       return of([]);
    })
  );


来源:https://stackoverflow.com/questions/41754106/angular2-rxjs-switchmap-catch-error

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