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

时间:2017-10-18 14:55:00

标签: angular http jwt angular-http-interceptors

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

对于JWT刷新,我扩展了Http类并覆盖request()方法(https://stackoverflow.com/a/45750985/2735398)。
现在我想对拦截器做同样的事情。

这是我现在的拦截器:

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请求?

1 个答案:

答案 0 :(得分:3)

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

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