在rxjs Angular 7中,在retry之后执行代码的位置在哪里?

huangapple go评论56阅读模式
英文:

Where to execute code that comes after retry in rxjs Angular 7

问题

我只回答代码部分的翻译,请看下面的内容:

// 我正在开发一个HTTP拦截器,如果刷新令牌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), // 如果刷新令牌() API返回错误,将尝试3次。
  catchError(error => {
    // 如果刷新令牌() API在3次重试后仍然未返回成功响应,我想要注销。
    this.authService.Logout();
    return throwError(error);
  })
);

希望这有助于您理解代码的翻译。

英文:

I'm working on an HTTP interceptor & I want to Logout my user if the refreshToken API fails after the retries.

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

My question is, am I doing the catchError correctly? I only want it to happen after it retries 3 times and still fails, but I'm worried that it will catchError before retrying.

答案1

得分: 0

是的,它应该仅在retry之后工作。此外,您可以将其放在catchError而不是订阅错误回调中。
这里是您用例的模拟:https://stackblitz.com/edit/typescript-kbfkq7

第一个订阅失败了多次,但在retry点之下 - 因此它会解析。
另一个在上面 - 因此会触发catchError和错误回调。

英文:

Yes, it should work only after retry. Also, you can put it not to catchError but to subscribe error callback.
Here is an simulation of your use-case: https://stackblitz.com/edit/typescript-kbfkq7

First subscription fails several times but is below retry point - so it resolves.

Another one is above - so catchError and error callback are emitted.

huangapple
  • 本文由 发表于 2020年1月3日 23:10:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定