#HttpInterceptor

1 messages · Page 1 of 1 (latest)

pallid rivet
#

I have a HttpInterceptor provided in the root config. I also have a component and a service for it. If I provide this service in the route file, my interceptor works and appends my bearer token. However if i provide this service in the component level. The interceptor does not work. Is there a way to fix this ? I am using a dynamic dialog so I cant add the service in the route file for my child component (so im providing the service in the child component itself)

pallid rivet
#

Previously, I was using a normal prime dialog in my parent component to display my child component
so in my parent component it is just
<div>......</div>
<p-dialog><child-component></child-component></p-dialog>

Everything was ok, because my service was provided in the route.ts for my parent and the child was in the same component file as my parent so my http interceptors able to append my bearer token to my child component when calling a service.

I am exploring dynamic component in primeng now so it will require a DialogService and I can display my child by something like
this.dialogService.open( ChildComponent) ....
so instead of directly having the child component in my parent, it is now opening the child component. Hence, my componentService for the child have to be provided in the ChildComponent,
But right now, after doing these changes my child's request does not get intercepted. Any idea how to fix this?
It would work if I provide dialogservice at the root app.config, but I would need it to be provided at a component level

This is how im implementing my interceptors

import { HttpInterceptorFn } from '@angular/common/http';

export const demoInterceptor: HttpInterceptorFn = (req, next) => {
  const authToken = 'YOUR_AUTH_TOKEN_HERE'; // im getting this from my session storage

  // Clone the request and add the authorization header
  const authReq = req.clone({
    setHeaders: {
      Authorization: `Bearer ${authToken}`
    }
  });

  // Pass the cloned request with the updated header to the next handler
  return next(authReq);
};


// app.config.ts

...
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { demoInterceptor } from './demo.interceptor';

export const appConfig: ApplicationConfig = {
  providers: [
    ...
    provideHttpClient(withInterceptors([demoInterceptor])),
  ],
};

pallid rivet
#

I managed to get it to work by providing DialogService at the route level for my parent component instead of in the parent component itself, ( note that i still have another dialogservice component in my child). But I dont really understand why..