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

左心房为你撑大大i 提交于 2020-04-10 04:12:26

问题


I have a working interceptor in Angular 5. It's registered in App.module's providers and correctly intercepts all requests made from the application.

The problem is that it doesn't intercept the requests made from the libraries used by the app.

I'm using an open source library (NGX-Jsonapi), and need the interceptor to provide a token in every request that the library makes to the back-end.

Someone faced the same issue?

EDIT: the library uses HttpClient.


回答1:


With version 4.3, angular added a new service HttpClient.
With version 5, angular deprecated the old service Http.

The interceptor only works with HttpClient.

You can be sure the libraries you have that are not intercepted, use the old Http. Pay attention, Http will probably be removed with angular 6!

If you want to make sure every call is intercepted by your interceptor, you need to upgrade your dependencies to their latest versions.




回答2:


Finally, I found the solution in 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.

I was importing HttpClientModule in a lazy loaded module that was making hte requests. After resolving this issue everything works like a charm.



来源:https://stackoverflow.com/questions/47794932/angular-5-interceptor-doesnt-intercept-requests-made-from-a-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!