It appears that having separate interceptors within an application is not possible, as confirmed through my experimentation detailed in the link below:
Interceptors-check
In my trial, I attempted:
- Importing Parent & Child Modules separately into the App component.
- Importing Child Module into Parent component and then importing Parent into App.
- Moving all services inside the modules, even if it meant duplicating code.
- Transferring the
HttpClientModule
from Parent and Child modules to the App module.
It seems that when we register interceptor(s), they are attached to the entire application rather than just a specific module.
Note: I removed my previous answer where I discussed a different approach, as it turned out to be incorrect.
If you wish to have distinct interceptors for various components, you can encapsulate them in separate modules and import one into another based on your requirements.
// child.module.ts
@NgModule({
...
declarations: [ChildComponent],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorTwo,
multi: true,
}],
exports: [ChildComponent]
})
export class ChildModule{}
// parent.module.ts
NgModule({
imports: [
... ,
ChildModule
],
providers: [
... , {
provide: HTTP_INTERCEPTORS,
useClass: InterceptorOne,
multi: true,
}],
...
})
export class ParentModule{}