Following is the interceptor in angular for replacing auth token.
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor(
) {
}
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token: string = localStorage.get('token');
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
return next.handle(request);
}
}
My app is structure like this:
--- app
---login // this is a routed module
---signup // this is a routed module
---main // this is a routed module
---profile // this is a routed child module
---items // this is a routed child module
Auth token will be available only after the login.
And I'm setting the interceptor for main module (i.e. provided in main module) (profile is where the user lands after login and sends requests based on received token)
But the issue here is that the interceptor is not getting called way before reaching the module.
So that when the profile component initialises and OnInit() I;m getting unauth response
& when I check the console I can see that the Authorization header is undefined.
How can I solve this?
NOTE I'm not providing it in root since this will spit out unauth error even before login. So I'm providing the interceptor only inside the main.module.ts file.
NOTE main module does not have any component with it. It is used only to register profile module and items module.
main module is getting loaded like this (from the root level):
{
path: '',
loadChildren: () => import('./main/main.module').then((m) => m.MainModule),
canActivate: [AuthGuard],
},