Angular2 rxjs - switchmap catch错误

blg*_*boy 8 rxjs angular

我希望能够在调用时处理任何错误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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

shu*_*son 20

使用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([]);
    })
  );
Run Code Online (Sandbox Code Playgroud)

  • 此方法在 v6 中 [重命名为 `catchError`](https://github.com/ReactiveX/rxjs/blob/master/docs_app/content/guide/v6/migration.md#howto-convert-to-pipe-syntax )。 (3认同)