【问题标题】:Angular 4 HTTP request from HTTP interceptor来自 HTTP 拦截器的 Angular 4 HTTP 请求
【发布时间】:2018-03-30 12:07:57
【问题描述】:

我正在尝试将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 请求?

【问题讨论】:

    标签: angular http jwt angular-http-interceptors


    【解决方案1】:

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

    【讨论】:

    • 如果我从“@angular/core”导入 { Injector },然后将“private injector: Injector”添加到构造函数中,我得到以下结果.....未捕获的错误:无法解决所有问题ResponseInterceptor 的参数:(?) -- 我是否需要以某种方式将其注入 app.module 中?
    • 我正是我所发现的,因为我正在实现令牌刷新:O
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2018-05-19
    • 1970-01-01
    • 2018-12-26
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多