【问题标题】:How to prevent duplicated requests for interceptor in Angular?如何防止Angular中的拦截器重复请求?
【发布时间】:2021-02-17 20:29:06
【问题描述】:

我有一个interceptor,它截获从200 OK 消息中收到的401 错误代码。

很遗憾,我无法修改 API 服务器以返回 401 错误而不是带有错误代码的 200 OK

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
  switchMap((result: any) => {
    //401 unauthorized error message
    if (result && result.body && result.body.isSuccess == false && result.body.errorCode == '401') {
      return this.unAuthorizedError(request, next);
    } else {
      return next.handle(request);
    }
  }),
  catchError((error) => {
    if (error instanceof HttpErrorResponse) {
      switch ((<HttpErrorResponse>error).status) {
        case 401:
        case 403:
          return this.unAuthorizedError(request, next);
        default:
          break;
      }
    }
    return throwError(error);
  })
);
}

问题是每个请求都会发送两次,我认为这是可能,因为switchMap 方法返回next.handle(request)

我试过tap方法

 tap((result: any) => {
    //401 unauthorized error message
    if (result && result.body && result.body.isSuccess == false && result.body.errorCode == '401') {
      return this.unAuthorizedError(request, next);
    }
  }),

只发送一次请求,但当令牌过期时,this.unAuthorizedError(request, next) 不会被调用。

【问题讨论】:

  • 你试过map吗?

标签: javascript angular rxjs request angular-http-interceptors


【解决方案1】:

我认为你是对的,next.handle(request); 所做的就是再次提出请求。

switchMap的内部observable被创建时,你已经有了响应,所以我想说你可以用of(response)替换next.handle(),这样它就可以被哪个部分发起请求:

/* ... */
return next.handle(request).pipe(
  switchMap((result: any) => {
    //401 unauthorized error message
    if (result && result.body && result.body.isSuccess == false && result.body.errorCode == '401') {
      return this.unAuthorizedError(request, next);
    } else {
      return of(result);
    }
  }),
)
/* ... */

我写了一篇关于 Angular 的 HTTPClientModulehere's 的文章,其中我谈到了拦截器。

【讨论】:

  • 是的,就在您发布答案前 2 分钟,我设法解决了这个问题。我的版本是from(of(result)),但我认为不再需要from 构造函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多