Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented 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();
// A clone is needed due to immutability of the HttpRequest.
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('Error: HTTP status code is 0.');
}
if (err.status !== 401) {
return;
}
this.authService.goToLogin();
}
}));
}
}
However, it appears that the header is not being attached to the outgoing request. Where could my mistake lie?
Furthermore, there are instances where the interceptor captures errorcode '0'. What does this signify?
Working with Angular version 8.2.11.
EDIT 1: ------------------------
I also attempted the following approach:
request = request.clone({
setHeaders: {
authorization: `Bearer ${token}`
}
});
Despite these efforts, the header remains unset. The module is correctly registered in app.module as well.
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor ,
multi: true,
}..
EDIT 2 : ------------------------
https://i.sstatic.net/pJtRK.png
Refer to this image... It's driving me insane.