Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 346
Maximiliano Cruz Avatar asked Dec 13 '17 14:12

Maximiliano Cruz


2 Answers

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.

like image 116
Maximiliano Cruz Avatar answered Nov 06 '22 03:11

Maximiliano Cruz


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.

like image 2
Deblaton Jean-Philippe Avatar answered Nov 06 '22 03:11

Deblaton Jean-Philippe