DEV Community

Angular: When HttpInterceptor doesn’t work with lazy loaded modules

Abou Kone on June 04, 2019

Http Interceptor working with a Lazy Loaded Module If you’re doing Angular the right way, you should be using some kind of httpinterceptor. An Ht...
Collapse
 
javarome profile image
Jérôme Beau

Thanks for this analysis Abou, this helped.

I had that problem too, but not caused by third-party modules. So I could solve by making sure that HttpClientModule is imported only once, in the AppModule (above/before the the lazy-loaded ones).

Collapse
 
karunalakshman profile image
KarunaLakshman

Hi Abou,

I believe if you use @SkipSelf() decorator for HttpClient service in lazy module, DI mechanism will inject the HttpClient service instance from parent injector. So your interceptor in parent injector might interceptor the service calls of lazy module. please give a try. I very often use @SkipSelf to access service instance from parent injector but haven’t tried especially for HttpClient service. This might help you. Good luck!!

Collapse
 
dudumanbogdan profile image
Duduman Bogdan Vlad

Shouldn't HttpClient send same instance from CoreModule? Meaning, why is needed the SkipSelf() in lazyModule

Collapse
 
jagpreetsingh83 profile image
jagpreetsingh83

I imported HttpClientModule in AppModule instead of the SharedModule and it worked for me.

Collapse
 
gidkom profile image
Gideon Kombian

this worked. thanks.

Collapse
 
_b0b1_ profile image
БоБи

Yes, that also worked for me.

Collapse
 
janatbek profile image
Janatbek

I had the same problem, in my case I was using HttpHandler and not HttpClient to avoid circular dependency. I noticed that I changed in all places, in the service in another module as well, which I shouldn't touch. so I put httpClient back and it worked.

Collapse
 
villanuevand profile image
Andrés Villanueva • Edited

Hi Abou,

Great explanation about the problem. This post and the comments bellow help me a lot to solve the problem.

Also I learned about the @Optional and @SkipSelf Decorators
In my cases I got interceptors in CoreModule.

I just moved the HttpClientModule to the CoreModule and removed form other Lazy loaded modules and it works pretty well.

Collapse
 
bgdnbc91 profile image
Bogdan

Hi Abou,

Nice post. I have the same issue with my interceptor. Did you find a solution for this issue after all?

Regards!

Collapse
 
villanuevand profile image
Andrés Villanueva

Hey @bogdan

You should move the HTTPClientModule to your CoreModule.