angular 4.3x 动态 http 拦截器

angular 4.3x dynamic http interceptor

我按照 this article 从 medium 创建了一个 http 拦截器,它允许我将 headers 添加到每个 http 调用

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

本文使用authService动态获取token。但是,一旦我将 HttpClient 注入 AuthService,我就会收到循环注入错误。

还有其他方法可以动态调整拦截器吗?

在 AngularJS 和 Angular 中避免循环依赖的传统方法是获取另一个提供程序实例 in-place 而不是在提供程序实例化时:

export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService, public injector: Injector) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const httpClient = injector.get(HttpClient);
    ...
  }
}

请注意,如果拦截器应用于所有 HttpClient 请求,它将应用于拦截器本身内部完成的请求,并可能导致无限递归。为了避免这种情况,可以将请求标记为跳过拦截器(例如通过自定义 header)。

article 它说:

It should be noted that Angular’s new HttpClient from @angular/common/http is being used here and not the Http class from @angular/http. If we try to make requests with the traditional Httpclass, the interceptor won’t be hit

请确保您在导入部分使用 import { HttpClient } from '@angular/common/http';

然后构造函数使用它:constructor(public http: HttpClient) {}