Angular 7 Error Interceptor – Problem with original call I've written an interceptor to catch all 401 errors. If such an error occurs it should try to get a new JWT token and if that worked repeat the original request. So far, the interceptor works. My problem is, that the orignal request after I gave it the new token doesn't end up in the subscribe again which was attached to the original observable.
Original Request
Component:
this.serviceModel.getSearchItems(si).subscribe(res => {
this.resultData = res;
});
ServiceModel
public getSearchItems(si: SearchInfo): Observable<VoList<SearchResultItemVO>> {
return this.post<VoList<SearchResultItemVO>>(`/api/Search/GetSearchItems`, si, null, SearchResultItemVO);
}
Intercepter
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private serviceModel: SharedAccountServiceModel) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).catch(err => {
return this.handleError(err, request, next);
});
}
handleError(err, request: HttpRequest<any>, next: HttpHandler) {
if (err.status === 401) {
if (!!localStorage.getItem('auth_token') && !!localStorage.getItem('refresh_token')) {
this.serviceModel.refreshlogin().switchMap(res => {
return next.handle(this.addAuthenticationToken(request));
})
.subscribe();
}
else {
localStorage.removeItem('accessinfo');
localStorage.removeItem('auth_token');
localStorage.removeItem('userid');
location.reload(true);
}
}
const error = err.error.message || err.statusText;
return throwError(error);
}
addAuthenticationToken(request) {
const accessToken = localStorage.getItem('auth_token');
if (!accessToken)
return request;
return request.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('auth_token')}`
}
});
}
}
From my understanding switchMap should contribute to the original subscribe being executed again, but it doesn't work. The call is executed but it does not arrive in the subscribe.