2017-08-11 107 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