2017-10-18 201 views
0

我正尝试将Http更新为更新的HttpClient来自HTTP拦截器的角度4 HTTP请求

对于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 ./[email protected]:-1 

延伸Http我可以打电话this.post(),因为我在Http实例本身工作。但是对于拦截器而言,这是无法完成的。

如何在拦截器内创建HTTP请求?

回答

0

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

如果我输入{注射器}从“@角/芯”,然后添加“私人喷射器:器”的构造,我得到以下.....未捕获的错误:无法解析ResponseInterceptor的所有参数:(?) - 我是否需要以某种方式将其注入到app.module中? – DigitalMystery