I'm trying to do http request inside the httpInterceptor, however it always falls in the catcherror, it is printed on the console the "fell into err".
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = localStorage.getItem('token');
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('token', authToken);
headers = headers.append('Authorization', 'bearer '+authToken);
if(authToken != null){
if(req.url !== AppSettings.API_ENDPOINT + 'plano/busca'){
let http: HttpClient = this.injector.get(HttpClient);
return http.get('api....', {headers: headers}).pipe(switchMap((response) => {
console.log('caiu no res')
console.log(response);
const newRequest = req.clone({
setHeaders: { Authorization: 'bearer ${authToken}', token: '${authToken}' }
});
return next.handle(newRequest);
}),
(err) => {
console.log('caiu no err');
if(err instanceof HttpErrorResponse) {
console.log(err)
return Observable.throw(err);
}}
)}else {
return next.handle(req);
}
}
}
@Edit:
I tried to make the request inside the service, now I get the request return, but it is not cloning the request and adding the header:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = localStorage.getItem('token');
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('token', authToken);
headers = headers.append('Authorization', 'bearer '+authToken);
if(authToken != null){
if(req.url !== AppSettings.API_ENDPOINT + 'plano/busca'){
let http: HttpClient = this.injector.get(HttpClient);
this.authService.validaPlano().subscribe((res) =>{
console.log(res);
if(res.data.vencido == true){
this.authService.Logout();
}else{
const newRequest = req.clone({
setHeaders: { Authorization: 'bearer ${authToken}', token: '${authToken}' }
});
return next.handle(newRequest);
}
},
(err) => {
if(err instanceof HttpErrorResponse) {
return Observable.throw(err);
}
})
}else {
return next.handle(req);
}
}
}
}
I have already checked and the headers are working correctly, I tested the postman and the request returns a response json ... Why might be falling into err?