0

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.

Multitut
  • 2,089
  • 7
  • 39
  • 63

1 Answers1

0

Here is how I do it:

export class JWTInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let headerName: string = 'Authorization';

        let authScheme: string = 'Bearer ';

        let token: string = localStorage.getItem('Token');

        return next.handle(() => {
            return request.clone({
                setHeaders: {
                    [headerName]: `${authScheme}${token}`
                }
            });
        });

    }

}
jlareau
  • 2,860
  • 1
  • 17
  • 11
  • Thanks! Is this an Angular 4 implementation? it tells me that I am missing 'url' in type '() => any'. Still, I integrated the setHeaders: { [headerName]: `${authScheme}${token}` } on my code but still don't see the token on the call – Multitut Aug 25 '17 at 15:05
  • I don't know about your warning. My code is almost copy pasted from working code on Angular 4.3.5. Are you sure your interceptor is loaded correctly? Maybe put a console.log to check. – jlareau Aug 25 '17 at 15:34
  • Everything else is working correctly, I checked my angular version and it is also 4.3.5. Could you provide your full example please? – Multitut Aug 25 '17 at 16:13
  • Not sure if this will do it, but have you tried removing the brackets from headerName? `[headerName]` -> `headerName`. I only glossed over this, but typically it's not looking for an array here. – Z. Bagley Aug 25 '17 at 17:46
  • Its not an array. It is how you define a computed property name on a object. See https://stackoverflow.com/questions/19837916/creating-object-with-dynamic-keys – jlareau Aug 25 '17 at 17:58
  • @Multitut are you sure you are using my code and not just copy pasting in yours? Because your example is wrong. You are setting headers in a HttpResponse instead of the Request. – jlareau Aug 25 '17 at 18:01