PPl here marking it duplicate rather reading this question... The link is how to add interceptor...that I am doing already and have posted code already, question is modifying headers to be sent in interceptor
Flow of application -
Login page - user logs in- gets a token and then in all http requests need to send that token.
Working sceario
var headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('X-Token', '123'); <-- read token from storage
return this.http.post(this.url + '/' + endpoint, body, {headers: this.headers});
but problem is I have to read that token everytime which is not needed, so I cahnged code to extend HttpInterceptor
export class AddHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Clone the request to add the new header
const clonedRequest = req.clone({ headers: req.headers.set('X-Token', 'a') });
// Pass the cloned request instead of the original request to the next handle
return next.handle(clonedRequest);
}
But question is does anyone know, how can I add that token at runtime, basically after user logs in and get that token , I need to update token in that interceptor.