1
I am trying to make http request inside httpInterceptor, but always falls in catcherror, is printed on the console the "crashed in 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 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 already checked and the headers are working correctly, I tested on Postman and the request returns a json sponse... 'Cause it might be falling into the err?
Request status is 20X? Type 200 or 204?
– Eduardo Vargas
It’s like 200 Eduardo
– I dont know code
I edited one with another attempt, this came closer
– I dont know code