As I delve into my first attempt at coding, I find myself faced with the challenge of capturing 401 errors using HttpInterceptor. My goal is to generate a new auth token based on a certain condition and then retry the process with that token in place. However, I am running into an issue where the retry happens before the new auth token is actually created. Here's a snippet of my code:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<any> {
return next.handle(request).catch(error => {
if (error.status === 401) {
console.log('401 error');
let refreshToken = localStorage.getItem('refresh_token');
this._refreshTokenService.getRefreshToken(refreshToken).subscribe(
refreshToken => {
if (refreshToken != null) {
console.log('valid refresh token')
console.log(localStorage.getItem('auth_token'));
this._userService.logout();
let email = localStorage.getItem('profile_email');
this._userService.autoLogin(email)
.subscribe(
result => {
if (result) {
console.log('new auth token created');
let auth_token = localStorage.getItem('auth_token');
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${auth_token}`) });
}
});
}
else {
console.log('invalid refresh token');
}
});
return next.handle(request);
}
else {
console.log(error.status);
}
});
}
While navigating through Typescript syntax, I've come to realize that I need to ensure the retry only takes place once the new token has been successfully generated. However, I'm uncertain about the specific syntax required to achieve this. Any guidance or assistance on this matter would be highly appreciated!