Define and export the jwtInterceptor
function as below: (save in jwtInterceptor.ts)
import { HttpRequest, HttpHandlerFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from '../services/auth.service'; // Replace with the actual path to your AuthService
export function jwtInterceptor(req: HttpRequest<any>, next: HttpHandlerFn) {
// Inject the AuthService to get the authentication token
const authToken = inject(AuthService).getToken();
// Clone the request and set the Authorization header
const newReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`),
});
// Pass the cloned request to the next handler
return next(newReq);
}
Configurein AppConfig.js like below:
import { jwtInterceptor } from './interceptor/jwtInterceptor';// Import the function
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(withEventReplay()),
provideHttpClient(withFetch(),withInterceptors([jwtInterceptor]),),
]
};
Note: Way to do int Angular 15+
That's it, you are set, Happy Conding !!
Cheers,
Kapil
No comments:
Post a Comment
Thanks for your comment, will revert as soon as we read it.