I would like to know how can I re-send the request with httpinterceptor after verification on error ?
I check if there is an error (to refresh my JWT token), and after the refresh I would like to submit again the fail request.
httpinterceptor.js :
import { Observable } from 'rxjs';
import { Injectable, Inject, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { UserService } from "./user/services/user.service";
import { Router } from "@angular/router";
@Injectable()
export class AngularInterceptor implements HttpInterceptor {
public userService;
constructor(private router: Router,
private injector: Injector) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const clonedRequest = req.clone();
this.userService = this.injector.get(UserService);
return next.handle(req)
.do(event => {
if (event instanceof HttpResponse) {
//normal request
console.log(event);
}
})
.catch((res) => {
console.log('catch error');
if (res.status === 401 || res.status === 403) {
this.userService.refreshToken().subscribe((data: any) => {
this.userService.token = data.token;
localStorage.removeItem('data-app');
localStorage.setItem('data-app', JSON.stringify({token: data.token}));
next.handle(clonedRequest).do(event => {
console.log('in handle');
if (event instanceof HttpResponse) {
console.log('rexecuted done !');
}
});
});
this.userService.logOut();
} else if (res.status === 500) {
console.log('token invalid');
return Observable.throw(res);
} else {
return Observable.throw(res);
}
});
}
}