Angular2 rxjs-switchmap捕获错误 [英] Angular2 rxjs - switchmap catch error

查看:157
本文介绍了Angular2 rxjs-switchmap捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

这篇关于Angular2 rxjs-switchmap捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆