【发布时间】:2018-01-19 20:20:28
【问题描述】:
如何向 Angular 4 应用程序添加多个独立的 HTTP 拦截器?
我尝试通过使用多个拦截器扩展 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 类,这应该可以。但是,我想避免这种情况,因为这些拦截器有完全不同的目的(一个用于错误处理,一个用于显示加载指示器)。
那么如何添加多个拦截器呢?
【问题讨论】:
-
你覆盖了
Http。仅使用最后一个覆盖。 Interceptor1 不会被忽略,它只是不存在。您可以使用包含拦截器的 HttpClient。 -
@estus “您可以使用包含拦截器的 HttpClient”是什么意思?
-
你可以对请求使用不同的拦截器,使用this响应你可以做错误处理,加载器指示器。
-
这个问题有更新吗?
标签: angular http interceptor angular-http-interceptors