Interceptor Angular 4.3 - Set multiple headers on the cloned request

39ro picture 39ro · Aug 7, 2017 · Viewed 35.6k times · Source

I just noticed that the Header Object that was possible to use in the previous HTTP RequestsOption is not anymore supported in the new Interceptor.

It's the new Interceptor logic:

// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});

I have, now, two ways to add my headers in this request:

Example:

headers?: HttpHeaders;

    headers: req.headers.set('token1', 'asd')

setHeaders?: {
   [name: string]: string | string[];
};

    setHeaders: {
             'token1': 'asd',
             'token2': 'lol'
    }

How can I add multiple headers conditionally on this request? Same to what I used to do with the Header Object:

 myLovellyHeaders(headers: Headers) {
    headers.set('token1', 'asd');
    headers.set('token2', 'lol');
     if (localStorage.getItem('token1')) {
     headers.set('token3', 'gosh');
     }
    }
    const headers = new Headers();
    this.myLovellyHeaders(headers);

Answer

non4me picture non4me · Oct 6, 2017

Angular 4.3+

Set multi headers in Interceptor:

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

import {environment} from '../../../../environments/environment';

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

    const headers = new HttpHeaders({
      'Authorization': 'token 123',
      'WEB-API-key': environment.webApiKey,
      'Content-Type': 'application/json'
    });


    const cloneReq = req.clone({headers});

    return next.handle(cloneReq);
  }
}