Angular is not aknowledging the interceptor.
So basically I executed
ng generate interceptor JwtInterceptor
and setup set it up to add the token to the header :
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';
export const jwtInterceptorInterceptor: HttpInterceptorFn = (req, next) => {
console.log('Interceptor invoked');
let token: string | null = localStorage.getItem("access_token");
console.log("Token from localStorage:", token);
if (token) {
const clonedRequest = req.clone({
headers: req.headers.set(
'x-auth-token',token
)
});
return next(clonedRequest).pipe(
catchError((err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
console.error('Unauthorized request:', err);
} else {
console.error('HTTP error:', err);
}
} else {
console.error('An error occurred:', err);
}
return throwError(() => err);
})
);
} else {
console.log("no token")
return next(req);
}
};
Then added the interceptor in the provider :
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(
withInterceptors([jwtInterceptorInterceptor]),
),]
};
also tried the Di pattern in app.config.ts :
export const appConfig: ApplicationConfig = {
providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(withInterceptorsFromDi()), {
provide: HTTP_INTERCEPTORS,
useValue: jwtInterceptorInterceptor,
multi: true
},]
};
And i even put the provider inside the component as well which shouldn't be done as it might double trigger it or cause a conflict i'm assuming :
@Component({
selector: 'app-profile',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './profile.component.html',
styleUrl: './profile.component.css',
providers: [
{
provide: HTTP_INTERCEPTORS,
useValue: jwtInterceptorInterceptor,
multi: true
}
],
})
I tried getting rid of all the interceptor's code and leaving only the loggings but still the interceptor is not being hit at all in any scenario :
Note
the app.config.ts was the wrong wrapper in which the intercepted should be callled, instead i called it in bootstrapApplication() in main.ts and it worked :
bootstrapApplication(AppComponent, {
providers: [
provideProtractorTestingSupport(),
provideRouter(routes),
provideAnimations(),
provideHttpClient(withInterceptors([jwtInterceptorInterceptor])),
],
}).catch((err) => console.error(err));