Search code examples
angularhttpclientangular-http-interceptors

How can I get access to HttpInterceptor from normal service?


Currently I need to create two instances of the same class to access some variables inside the HttpInterceptor. Is there a way to resolve the provider with just one instance and allows me to use the same interceptor class in normal service and as interceptor?

*.module.ts

.
.
Providers:[
 CustomInterceptor, // first class instance
 {
  Provide: HTTP_INTERCEPTORS,
  UseClass: CustomInterceptor, // second class instance
  multi: true,
 }
],
.
.

http.service.ts

constructor(
 interceptor: CustomInterceptor,
){}

interceptor.hasNext$.next(true);

CustomInterceptor.ts

hasNext$ = new BehaviourSubject(false);

When I call the interceptor in the http.service.ts, I access the first CustomInterceptor while the request I make to the httpClient is the second instance of CustomInterceptor. Therefore my hasNext$.next(true) in the http.service.ts will never change in the second one.

Someone suggested that I should use,

Providers: [
 CustomInterceptor,
 {
  provide: HTTP_INTERCEPTORS,
  useValue: CustomInterceptor,
  multi: true,
 },
]

but the above code will throw an error, because HTTP_INTERCEPTORS token requeires useClass and base on my understanding that will class an instance of the same class.

UPDATE

Just found a way to write to work around this.

http.service.ts

constructor(
 @Inject(HTTP_INTERCEPTOS) protected interceptor: CustomInterceptor,
){}

interceptor.hasNext$.next(true);

Solution

  • Other way to get this to work without having to instantiate other token in the provider is manually inject the HTTP_INTERCEPTORS in the normal service.

    app.moudule.ts

    providers: [
     {
       provide: HTTP_INTERCEPTORS,
       useClass: CustomInterceptor,
       multi: true,
     }
    ],
    

    http.service.ts

    constructor (
     @Inject(HTTP_INTERCEPTORS) private interceptors: HttpInterceptors,
    ) {
     let interceptor = interceptors.find(x => x instanceOf CustomInterceptor);
     interceptor.hasNext$.next(true); // this way we have access to the same interceptor
    }