4

I'm trying to make a jsonwebtoken interceptor and for some reason it doesn't set the header at all.

For my providers I have

import { TokenInterceptorService } from './token-interceptor.service';
...
providers: [AuthService, AuthGuard, {
        provide: HTTP_INTERCEPTORS,
        useClass: TokenInterceptorService,
        multi: true
}]

as my TokenInterceptorService is pretty simple too:

import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor {

    constructor() { }

    intercept(req, next) {

        let tokenizedReq = req.clone({
            setHeader: {
                Authorization: 'Bearer xx.yy.zz'
            }
        })

        return next.handle(tokenizedReq);
    }
}

if I log tokenizedReq the headers have nothing. I must be overlooking something.

1
  • Is service lazy loaded? Commented Aug 28, 2018 at 7:14

3 Answers 3

8

Not setHeader but setHeaders - in plural form

let tokenizedReq = req.clone({
     setHeaders: {
         'Authorization': 'Bearer xx.yy.zz'
     }
})
Sign up to request clarification or add additional context in comments.

2 Comments

Extremely upset at myself as I spent two hours on this. Thank you.
This is programming :)
2

setHeader is nothing.

Either use setHeaders: {} like

        let tokenizedReq = req.clone({
            setHeaders: {
                Authorization: 'Bearer xx.yy.zz'
            }
        })

or use

    let tokenizedReq = req.clone({
        headers: req.headers.set('Authorization','Bearer xx.yy.zz'),
    })    

Comments

0

Try with the help of Observable.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
    request = request.clone({
      setHeaders: {
        Authorization: 'Bearer xx.yy.zz'
      }
    });
    return next.handle(request);
  }

2 Comments

I'm quite new to Angular and Typescript. What help do observables give me in this compared to not using them at all like I am now? I've Googled Observables plenty of times, but never really found "why" I'd need it.
angular.io/guide/observables-in-angular : This link help you to understand what is observable, and what are the advantage of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.