2017-10-18 205 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