How to add multiple headers in Angular 5 HttpInterceptor

Fel picture Fel · Feb 8, 2018 · Viewed 49.7k times · Source

I'm trying to learn how to use HttpInterceptor to add a couple of headers to each HTTP request the app do to the API. I've got this interceptor:

import { Injectable } from '@angular/core';

import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';


@Injectable()
export class fwcAPIInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const authReq = req.clone({
      headers: req.headers.set('Content-Type', 'application/json')
    });

    console.log('Intercepted HTTP call', authReq);

    return next.handle(authReq);
  }
}

Apart of the 'Content-Type' header I need to add an 'Authorization' but I don't how to do it (the documentation of Angular HttpHeaders is just the list of the methods, without any explanation).

How can I do it? Thanks!

Answer

Ketan Patil picture Ketan Patil · Apr 11, 2018

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')
});