I am try to implement refresh token in angular, the problem is the subscribe method of api get executed before getting the refresh token from the api if the token is expired. Here is the snapshot of my code. I don't understand what's wrong i am doing here
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const token = this.storage.getItem(USER_CONST.ACCESS_TOKEN);
const hasRefreshToken = request.url.includes("refreshToken");
const httpOptions = {
headers: new HttpHeaders({
'content-type': 'application/json',
'x-channel-id': 'INT',
'x-trans-id': '1010111111101011111110101111111010111111145241',
Accept: 'application/json, text/plain, */*'
})
};
if (!hasRefreshToken) {
httpOptions.headers = httpOptions.headers.set('x-access-token', ` ${token}`);
} else {
const refreshToken = this.userService.getRefreshToken();
httpOptions.headers = httpOptions.headers.set('x-refresh-token', ` ${refreshToken}`);
}
const clonedRequest = request.clone(httpOptions)
return next.handle(clonedRequest)
.pipe(tap(
(data) => {
if (data && data['body'] && data['body']['exception'] && data['body']['exception'][0].description) {
if (data['body']['exception'][0].name === 'TOKEN_INVALID') {
const URL = `${environment.API_BASE_URL}${REFRESH_URL}`
return this.http.post(URL, null, { observe: 'response' })
.pipe(switchMap(
(response: any) => {
const exception = response['body'].exception ? response['body'].exception[0] : null;
if (exception && (exception.name === 'REFRESH_TOKEN_INVALID' || exception.name === 'REFRESH_TOKEN_EXPIRED')) {
return this.router.navigateByUrl('auth/login')
}
this.userService.setAccessToken(response.headers.get('x-access-token'));
this.userService.setRefreshToken(response.headers.get('x-refresh-token'));
const requestClone = request.clone();
return next.handle(requestClone);
}
))
}
}
}));
}
And this is the subscribe method that gets executed first.