【问题标题】:Angular2 rxjs - switchmap catch errorAngular2 rxjs - switchmap 捕获错误
【发布时间】:2017-01-20 00:26:17
【问题描述】:

我希望能够处理调用this.authService.refreshToken() 时出现的任何错误。是否可以在 switchmap 块中处理错误,或者在这种情况下如何处理错误?

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

【问题讨论】:

  • 顺便说一句,你需要一个回报:return Observable.throw(data);

标签: angular rxjs


【解决方案1】:

使用catchError 方法

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([]);
    })
  );

【讨论】:

猜你喜欢
  • 2016-12-05
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-05
  • 2020-06-25
  • 1970-01-01
相关资源
最近更新 更多