Have you ever wished to split your application into business modules (feature modules) so that they each have their own set of feature logic http interceptors, yet they are so decoupled they can still use common logic interceptors without knowledge or reference to it.

Maybe different teams work in different features and have different Angular projects (I hope they are not building a huge unmaintainable monolith), and these projects export independently tested modules which are lazy loaded into the main application. Maybe some other similar use case 🤔…

Say something particular only to the feature module needs to be done on every http request, but the common interceptors still need to be applied, those that complete the URLs for REST api endpoints, and the interceptor that adds customs headers. If there even are interceptors for that 🤨, the feature module dev team shouldn’t really need to know of the core module workings. It is akin to  inversion of control.

The way Angular has been working (as of Angular v11) is that the interceptors for a lazy loaded module either are ignored or are applied by themselves in isolation.

For a little more insight into why, here comes the explanation: since a  lazy loaded module creates a child injector, the interceptors provided are a set contained for this child injector. Hence, they are ignored if the import of HttpClientModule was kept only to the parent module because when injecting the service HttpClient from the parent injector, it does not see the set of interceptors that are in the child injector. On the other hand, they are isolated if HttpClientModule was re-imported in the child module, thus creating a new instance of the service which sees only the set of interceptors in the same injector but not those in the parent.

#javascript #programming #angular

Extending HTTP Interceptors Hierarchically in Angular
3.95 GEEK