2017-08-11 59 views
17

如何向Angular 4應用程序添加多個獨立HTTP攔截器?將多個HTTP攔截器添加到Angular應用程序

我試圖通過擴展providers數組並添加多個攔截器來添加它們。但只有最後一個實際執行,Interceptor1被忽略。

@NgModule({ 
    declarations: [ /* ... */ ], 
    imports: [ /* ... */ HttpModule ], 
    providers: [ 
    { 
     provide: Http, 
     useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => 
     new Interceptor1(xhrBackend, requestOptions), 
     deps: [XHRBackend, RequestOptions], 
    }, 
    { 
     provide: Http, 
     useFactory: (xhrBackend: XHRBackend, requestOptions: RequestOptions) => 
     new Interceptor2(xhrBackend, requestOptions), 
     deps: [XHRBackend, RequestOptions] 
    }, 
    ], 
    bootstrap: [AppComponent] 
}) 
export class AppModule {} 

我能明顯它們合併成一個單一的Interceptor類,並應工作。但是,我想避免這種情況,因爲這些攔截器有完全不同的目的(一個用於錯誤處理,一個用於顯示加載指示器)。

那麼如何添加多個攔截器?

+1

你正在重寫'Http'。只使用最後的覆蓋。 Interceptor1不被忽略,它只是不存在。您可以使用包含攔截器的HttpClient。 – estus

+0

@estus你的意思是「你可以使用包含攔截器的HttpClient」。 – str

+0

https://angular.io/guide/http – estus

回答

36

Http不允許有多個自定義實現。但是@estus提到Angular團隊最近增加了一個新的HttpClient服務(版本4.3),該服務支持多個攔截概念。您不需要像舊版Http那樣擴展HttpClient。您可以爲HTTP_INTERCEPTORS而不是實現它可與'multi: true'選項的數組:

import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http'; 
... 

@NgModule({ 
    ... 
    imports: [ 
    ... , 
    HttpClientModule 
    ], 
    providers: [ 
    ... , 
    { 
     provide: HTTP_INTERCEPTORS, 
     useClass: InterceptorOne, 
     multi: true, 
    }, 
    { 
     provide: HTTP_INTERCEPTORS, 
     useClass: InterceptorTwo, 
     multi: true, 
    } 
    ], 
    ... 
}) 

攔截器:

import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; 
... 

@Injectable() 
export class InterceptorOne implements HttpInterceptor { 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    console.log('InterceptorOne is working'); 
    return next.handle(req); 
    } 
} 

@Injectable() 
export class InterceptorTwo implements HttpInterceptor { 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    console.log('InterceptorTwo is working'); 
    return next.handle(req); 
    } 
} 

此服務器的通話將同時打印攔截器的日誌消息:

import {HttpClient} from '@angular/common/http'; 
... 

@Component({ ... }) 
export class SomeComponent implements OnInit { 

    constructor(private http: HttpClient) {} 

    ngOnInit(): void { 
    this.http.get('http://some_url').subscribe(); 
    } 
} 
+0

有沒有辦法告訴'api'調用只能被一個攔截器攔截?或任何條件? – k11k2