Angular 4 HTTP 拦截器中的 HTTP 请求

3
我正在尝试将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个回答

6
你可以从 @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);
    });
  }
}

1
如果我从 "@angular/core" 导入 { Injector },然后在构造函数中添加 "private injector: Injector",我会得到以下错误信息..... Uncaught Error: Can't resolve all parameters for ResponseInterceptor: (?) -- 我需要在 app.module 中注入它吗? - DigitalMystery
我找到了我想要的,因为我正在实现令牌刷新 :O - Richard Aguirre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接