I have two interceptors -- MainInterceptor
and OptionalInterceptor
.
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: MainInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: OptionalInterceptor, multi: true }
];
and I provide them in app.module
:
providers: [
...
httpInterceptorProviders
]
The logic inside OptionalInterceptor
should be executed only in specific conditions (depending on the value of a cookie). I have a service ConfigService
that reads the cookie and knows the condition.
Right now I inject this service in OptionalInterceptor
and execute the logic or not depending on service state.
However the cookie is available (or not) at load time, hence it feels it would be cleaner not to load the OptionalInterceptor
at all.
I could create NoopInterceptor
and do something like:
export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: MainInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useFactory: (srv: ConfigService) => srv.optional ? OptionalInterceptor: NoopInterceptor, multi: true, deps: [ConfigService] }
];
but it does not feel any better.
Finally I could define httpInterceptorProviders
as a factory:
export const httpInterceptorProviders = (srv: ConfigService) => {...}
in this case I do not see how can I inject the service in module:
httpInterceptorProviders(injectedService)
or
{provide: ???, useFactory: httpInterceptorProviders, deps:[ConfigService]}
Well there is also an approach from this answer. It provides different HttpClient instances injected with different interceptors, but for a simple case this solution looks worse than the problem. It strictly gets the job done, but with even less elegance than doing ifs to skip the logic or creating a NoopInterceptor
.
(edit) Just to clarify: why I prefer forcing to load interceptors conditionally instead of applying the condition in the interceptor code? I regard applying condition during the loading of the interceptor to be more clear and maintainable. In order to avoid questions like "why our interceptor is not working, is it broken?" and going to the interceptor code for answer.