How to add multiple headers in Angular 5 HttpInterceptor
Solution 1:
Since the set
method returns headers object every time, you can do this. This way, original headers from the intercepted request will also be retained.
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
Solution 2:
Edit: Following suggestions in comments I have unified both answers
Overwriting all headers
@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
intercept (req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token'
})
});
console.log('Intercepted HTTP call', authReq);
return next.handle(authReq);
}
Adding more headers without overwriting (credits to Ketan Patil - see answer in this post)
const authReq = req.clone({
headers: req.headers.set('Content-Type', 'application/json')
.set('header2', 'header 2 value')
.set('header3', 'header 3 value')
});
Solution 3:
As mentioned before - accepted method overrides headers, for adding them I like approach from API documentation:
const authReq = req.clone({ setHeaders: { Authorization: authToken } });