I have a HttpInterceptor on my Angular 4 app that is working pretty good. But something I want to achieve here as well is to inject a JSON web token when available, but I haven't found the right way to do it, please check the code below:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable} from "rxjs";
import {ToasterService} from "angular2-toaster";
import 'rxjs/add/operator/do';
@Injectable()
export class GobaeInterceptor implements HttpInterceptor {
constructor(private toasterService: ToasterService){
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
next.handle(req).subscribe(event => {
if (event instanceof HttpResponse) {
if (localStorage.getItem('Token')) {
//THIS ISN'T WORKING:
event.headers.append('authentication', `${localStorage.getItem('Token')}`);
}
let response = event.body;
if(response.Error){
this.toasterService.pop('error', 'Error '+response.Code, response.Message);
}
}
}, error => {console.log(error)});
return next.handle(req);
}
}
It doesn't rise any errors but it dosn't set it either (I checked the requests on the network tab). Also I tried to pass a hardcoded string instead of getting it from localStorage with the same result.