I am using an Interceptor in my application, when the token is expired (401 returned), I want to refresh the token, save the new token to localstorage
and then continue the request with the new token.
Catching the 401 error works, and I am able to get a new token but the request still fails with a 401 and doesn't work UNTIL I refresh the page.
This is the code for the intercept method currently using:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('Interceptor called===============>');
const token = localStorage.getItem(environment.TOKEN_NAME);
if (token) {
const headers = { Authorization: `Bearer ${token}` };
Object.keys(AppHttpInterceptor.headers).forEach((header) => {
// @ts-ignore
if (!AppHttpInterceptor.headers[header]) {
return;
}
// @ts-ignore
headers[header] = AppHttpInterceptor.headers[header];
});
request = request.clone({ setHeaders: headers });
}
const handled: Observable<HttpEvent<any>> = next.handle(request);
const subject: AsyncSubject<HttpEvent<any>> = new AsyncSubject();
handled.subscribe(subject);
subject.subscribe((event: HttpEvent<any>) => {
if (event instanceof HttpErrorResponse) {
if (event.status === 401) {
return;
}
this.httpError.emit(event);
}
}, (err: HttpEvent<any>) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
this.tokenRefreshService.refreshToken().subscribe(response => {
const headers = { Authorization: `Bearer ${localStorage.getItem(environment.TOKEN_NAME)}` };
console.log('HEADERS ======> ' + headers);
// @ts-ignore
Object.keys(AppHttpInterceptor.headers).forEach((header) => {
// @ts-ignore
if (!AppHttpInterceptor.headers[header]) {
return;
}
// @ts-ignore
headers[header] = AppHttpInterceptor.headers[header];
});
request = request.clone({ setHeaders: headers });
});
return;
}
if (err.status === 404) {
return;
}
this.httpError.emit(err);
}
});
return Observable.create((obs: Observer<HttpEvent<any>>) => {
subject.subscribe(obs);
});
}
Is this the right approach?