Angular 4 来自 HTTP 拦截器的 HTTP 请求

Angular 4 HTTP request from HTTP interceptor

我正在尝试将 Http 更新到较新的 HttpClient

为了刷新 JWT,我扩展了 Http class 并覆盖了 request() 方法()。
现在我想对拦截器做同样的事情。

这是我现在拥有的拦截器:

export class JwtRefreshInterceptor implements HttpInterceptor {

  public constructor(
    private httpClient: HttpClient,
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).catch((error: HttpErrorResponse) => {
      if (error.status === 401) {
        return this.httpClient.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => {
          // get token from response.
          // put token in localstorage.
          // add token to the request.

          // Do the request again with the new token.
          return next.handle(request);
        });
      }

      return Observable.throw(error);
    });
  }
}

问题是我无法注入 HttpClient 因为我得到一个错误:

Provider parse errors:
Cannot instantiate cyclic dependency! InjectionToken_HTTP_INTERCEPTORS ("[ERROR ->]"): in NgModule AppModule in ./AppModule@-1:-1

通过扩展 Http 我可以调用 this.post() 因为我在 Http 实例本身中工作。但是对于拦截器,这是无法完成的。

如何在拦截器中发出 HTTP 请求?

您可以从 @angular/core 注入 Injector 并在需要时获取依赖项:

export class JwtRefreshInterceptor implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).catch((error: HttpErrorResponse) => {
      if (error.status === 401) {
        const http = this.injector.get(HttpClient);
        return http.post(environment.base_uri + 'auth/refresh', {}).flatMap((response) => {
          // get token from response.
          // put token in localstorage.
          // add token to the request.

          // Do the request again with the new token.
          return next.handle(request);
        });
      }

      return Observable.throw(error);
    });
  }
}