Angular 5 拦截器不拦截来自库的请求

Angular 5 Interceptor doesn't intercept requests made from a library

我在 Angular 5 中有一个工作拦截器。它在 App.module 的提供程序中注册并正确拦截从应用程序发出的所有请求。

问题是它不会拦截从应用程序使用的库发出的请求。

我正在使用开源库 (NGX-Jsonapi),并且需要拦截器在库向后端发出的每个请求中提供令牌。

有人遇到同样的问题吗?

编辑:库使用 HttpClient。

在 4.3 版中,angular 添加了一项新服务 HttpClient
在版本 5 中,angular 弃用了旧服务 Http

拦截器仅适用于 HttpClient

你可以确定你拥有的库没有被拦截,使用旧的Http。注意,Http 可能会被 angular 6!

删除

如果您想确保每个调用都被您的拦截器拦截,您需要将您的依赖项升级到最新版本。

最后,我在Angular HttpInterceptor documentation usage notes中找到了解决方案:

To use the same instance of HttpInterceptors for the entire app, import the HttpClientModule only in your AppModule, and add the interceptors to the root application injector . If you import HttpClientModule multiple times across different modules (for example, in lazy loading modules), each import creates a new copy of the HttpClientModule, which overwrites the interceptors provided in the root module.

我在一个发出 hte 请求的延迟加载模块中导入 HttpClientModule。解决此问题后,一切正常。