0
votes

I have to put a token inside the 'Authorization' header for every HTTP request. So I have developed and registered an HttpInterceptor :

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public authService: AuthService) {
  }  

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

    let modifiedReq;
    const token = this.authService.getToken();

    // we need the heck clone because the HttpRequest is immutable
    // https://angular.io/guide/http#immutability
    if (token) {
      modifiedReq = request.clone();
      modifiedReq.headers.set('Authorization', `Bearer ${token}`);
    }

    return next.handle(modifiedReq ? modifiedReq : request).pipe(tap(() => {
        // do nothing
    },
    (err: any) => {
    if (err instanceof HttpErrorResponse) {
      if (err.status === 0) {
        alert('what the heck, 0 HTTP code?');
      }
      if (err.status !== 401) {
        return;
      }
      this.authService.goToLogin();
    }
  }));
 }
}

But the header seems never to be put on the request sent. What am I doing wrong?

Also, sometimes an errorcode '0' gets caught by the interceptor; what does it mean?

Angular 8.2.11

EDIT 1: ------------------------

I've also tried like this:

request = request.clone({
            setHeaders: {
                authorization: `Bearer ${token}`
            }
        }); 

but still no header has been set. Also, the module is correctly registered in app.module

 providers: [{
   provide: HTTP_INTERCEPTORS,
   useClass: TokenInterceptor ,
   multi: true,
 }..

EDIT 2 : ------------------------

debugger

Check this image... I'm going crazy.

3

3 Answers

0
votes

It's working for me like this:

const headersConfig = {
  'Accept': 'application/json', //default headers
};
...

if (token) {
  headersConfig['Authorization'] = `Bearer ${token}`;
}
...

return next
  .handle(request.clone({
     setHeaders: headersConfig
  }))
0
votes

maybe you forget to put in app.module this:

  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor ,
    multi: true,
  }..

the final part write in this way:

 return next.handle(modifiedReq);
0
votes

I was wrong. When doing update of the clone request, angular will put the new headers in fields called "lazyUpdate" and not direcly inside the headers. The requests were failing because of other reasons.