EDIT: This problem does not occur when you import
HttpClientModule only ONCE in the
CoreModule (and import the
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! 😃