Angular Interceptor authorization: headers are now immutable

In Angular 4, headers are immutable, so to add (say) an Authorization header in your interceptor you have to use a cunning overload of the .clone method.

My complete interceptor looks like this…

import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
//import { FafService } from "./faf-service";
import { Injectable } from "@angular/core";
@Injectable()
export class FafInterceptor implements HttpInterceptor{
public theToken:string = null;
constructor(){
}
intercept(request: HttpRequest, next: HttpHandler): Observable<HttpEvent>
{
let theToken = window.localStorage.getItem('theToken');
//TODO: IsGuid
if(theToken && theToken != 'null'){
var NewRequest = request.clone(
{
setHeaders:{'Authorization': 'Bearer ' + theToken}
}
);
//https://angular.io/api/common/http/HttpRequest
console.log('auth header now ' + NewRequest.headers.get('Authorization'));
return next.handle(NewRequest);
}
return next.handle(request);
}
}

Website by WNW Digital