I am trying to implement an access_token/refresh_token into my Http Interceptor in Angular5. The problem I have is I cannot do the call again after I get the refresh token. So, when I get a 401 error (access_token expired), I get a new access_token using the refresh_token and everything works fine until here. Next, I should do the initial call again using the new access_token, so I am trying to do this with the second
return next.handle(req);
but this doesn't work. So when I click on the first time and the token is expired, the application successfully gets a new token and writes it into localStorage, but the initial call is not being made again. If I click again, the initial call is being made successfully (with the new access token which was stored properly on the previous click). It's like I cannot get out of the catch. Maybe I am doing a stupid mistake.
Bellow is my code.Please advise. Thanks!
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<any> {
let access_token, refresh_token;
if (localStorage.currentUser) {
access_token = JSON.parse(localStorage.currentUser).access_token;
refresh_token = JSON.parse(localStorage.currentUser).refresh_token;
if(access_token){
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + access_token) });
}
}
return next.handle(req)
.catch((error, caught) => {
if (this.isAuthError(error)) {
return this._auth.getRefreshToken().map((resp) => {
let user = resp.json();
localStorage.setItem('currentUser', JSON.stringify(user));
access_token = JSON.parse(localStorage.currentUser).access_token;
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + access_token) });
return next.handle(req);
});
} else {
return Observable.throw(error);
}
})
}