我正在尝试向现有的 Angular 应用程序添加 HTTP 拦截器。
重点是,它已经提供了一个拦截器:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor,
multi: true
},
AuthGuard, AuthService, AuthenticationInterceptor],
据我所知,拦截概念,它们可以通过管道相互连接。因此我尝试了这个:
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: CustomInterceptor, // existing interceptor
multi: true
}, AuthGuard, AuthService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthenticationInterceptor, // my interceptor
multi: true
}],
事情正在进展。但我不确定我是否已经覆盖了现有的拦截器。在 Angular 5 中注册多个拦截器可以吗?它们会互相抵消吗?或者它们只是作为管道中的工作站工作并相互增强?
最佳答案
TL;DR 是的,提供多个拦截器就可以了,而且它们是按顺序运行的。
But I'm not sure if I've overridden the existing interceptor or not.
通过运行代码并检查,您可以查看是否发生这种情况。无论如何,documentation明确指出可以有多个拦截器,因为它讨论了它们的顺序:
Angular applies interceptors in the order that you provide them. If you provide interceptors A, then B, then C, requests will flow in A->B->C and responses will flow out C->B->A.
在同一文档的上面几段中,还解释了 multi
选项与此相关:
Note the multi: true option. This required setting tells Angular that HTTP_INTERCEPTORS is a token for a multiprovider that injects an array of values, rather than a single value.
可以找到此标志的文档 here .
关于angular - Angular 5 中可以注册多个拦截器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433426/