I have created httpInterceptor in backend SpringBoot and keeping my API key in application.properties.
I have to enable HttpInterceptor somewhere in Angular service in Http header but I dont know how I can do it
CodePudding user response:
you mean how to register you interceptor? you can add it as provider in your module:
@NgModule({
imports: [
HttpClientModule
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: BackendRequestInterceptor, multi: true},
CodePudding user response:
Yes! Register the interceptor like Andreas posted in his answer and then implement it. Here is an example from one of my projects:
import { Injectable } from "@angular/core";
import { HttpInterceptor } from '@angular/common/http';
import { AuthDirectusService } from './auth-directus.service';
@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
constructor(private authService: AuthDirectusService) {}
intercept(req, next) {
if(this.authService.getToken() != null)
{
let tokenizedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${this.authService.getToken()}`
}
})
return next.handle(tokenizedReq);
}else{
let tokenizedReq = req.clone({
setHeaders: {
}
})
return next.handle(tokenizedReq);
}
}
}