首页 > 解决方案 > 在 rxjs Angular 7 中重试后在哪里执行代码

问题描述

我正在使用 HTTP 拦截器,如果在重试后 refreshToken API 失败,我想注销我的用户。

    return this.authService.refreshToken().pipe(
      switchMap((token: any) => {
        console.log(token);
        this.isRefreshing = false;
        this.refreshTokenSubject.next(token.accessToken);
        return next.handle(this.addToken(req, token.accessToken));
      }),
      retry(3), //Tries the refreshToken() API if it returns with an error.
      catchError(error => {
      //If the refreshToken() API never returns a successful response, I want to Logout.
        this.authService.Logout();
        return throwError(error);
      }
    );

我的问题是,我正确地执行了 catchError 吗?我只希望它在重试 3 次但仍然失败后发生,但我担心它会在重试之前捕获错误。

标签: angularrxjs

解决方案


是的,它应该只在retry. 此外,您可以不订阅错误回调,catchError而是订阅错误回调。这是您的用例的模拟:https ://stackblitz.com/edit/typescript-kbfkq7

第一次订阅失败了几次,但低于retry点 - 所以它解决了。

另一个在上面 - 所以catchError会发出错误回调。


推荐阅读