That's why your Angular Interceptor may NOT WORK! π₯ [5 seconds fix]
Bartosz Pietrucha
Posted on November 8, 2019
EDIT: This problem does not occur when you import HttpClientModule
only ONCE in the AppModule
or CoreModule
(and import the CoreModule
into AppModule
). Huge Kudos to @joekaiser for spotting the issue! πππ
It's time for another Angular Knowledge Pill!
It takes just a couple of seconds to learn something new π₯
Like taking your morning vitamins π
π Angular creates a new Dependency Injector for a lazy-loaded module!
So what!? π€ For example, your HttpErrorInterceptor (or TokenInterceptor) may not work as you expect! Let's take a closer look. We have three modules CoreModule, AuthModule, and ExpensesModule. The first two modules are NOT lazy-loaded and register interceptors. The third, ExpensesModule is lazy-loaded and uses HttpClient to execute HTTP requests.
The solution π @SkipSelf()
Now, if we have ExpensesModule (lazy-loaded) and if we don't use @SkipSelf() when injecting HttpClient into a provider (here ExpenseApi), Angular will create a new instance WITHOUT previously registered HttpInterceptors - Error handling will not work! π€¦ββοΈ Take a look at how to tell Angular not to create a new instance of a provider in the lazy-loaded module!
That's it! Problem is fixed! Your Interceptors are working properly πͺ.
If you would like to receive this kind of knowledge pills directly into your mailbox, subscribe at angular-academy.com/blog/. I will be sending them regularly! Remember, it just takes 10 seconds to learn something new! π
Posted on November 8, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 31, 2024