I have set up an HttpInterceptor to include an Authorization Header Token and I am attempting to handle http errors. However, the Authorization header is not being sent. Everything was working correctly before I added the error handler. I have also made sure to register my interceptor in the AppModule.
// Here is my interceptor.ts code snippet
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler,
HttpRequest, HttpErrorResponse} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError} from "rxjs/internal/operators";
import {ToastrService} from "ngx-toastr";
@Injectable()
export class MyInterceptor implements HttpInterceptor {
constructor(private toastService: ToastrService)
{
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let reqHeader;
if(sessionStorage.getItem('token') !== null || sessionStorage.getItem('token') !== undefined)
reqHeader = req.clone({headers: req.headers.set('Authorization',
sessionStorage.getItem('token'))});
else
reqHeader = req.clone({headers: req.headers.set('Authorization', "123")});
return next.handle(req).pipe(catchError((error, caught) => {
console.log(error);
this.handleAuthError(error);
return of(error);
}) as any);
}
/**
* manage errors
* @param err
* @returns {any}
*/
private handleAuthError(err: HttpErrorResponse): Observable<any> {
//handle your auth error or rethrow
console.log(err);
this.toastService.error("Error Received","Err");
throw err;
}
}
// Here is my App Module.ts code snippet
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true,
}