This is my getRefreshToken
method from service:
getRefreshToken(): Observable<AuthResponse> {
return this.http.post<AuthResponse>(
`${environment.WEBSITE_API_NEW_URL}/${environment.NEW_REFRESH_AUTH_TOKEN_PARAM}`,
{},
{ observe: 'response' }
).pipe(
map((response) => {
if (response.status === 200) {
const data = response.body;
this.storage.set('access_token', data.accessToken);
this.storage.set('refresh_token', data.refreshToken);
this.storage.set('ttl', (Date.now() + 5 * 1000).toString());
return data;
}
throw new Error('Failed to refresh token');
}),
catchError((error) => {
console.error('Error refreshing token:', error);
// this.logout();
return throwError(error);
})
);
}
And this is my handleTokenExpired
method in interceptor:
private handleTokenExpired(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
return this.authService.getRefreshToken().pipe(
switchMap(() => {
const newAccessToken: string = this.storage.get('access_token');
const newRefreshToken: string = this.storage.get('refresh_token');
return next.handle(this.addToken(req, newAccessToken, newRefreshToken));
}),
catchError((error) => {
console.error('Error handling expired access token:', error);
return throwError(error);
}),
);
}
In this way, HTTP request from getRefreshToken
is not triggered, and when I put subscribe
instead of pipe
, I am getting error in handleTokenExpired
that pipe does not exist on Subscription. Can somebody help?
3
In your setup with pipe, the handleTokenExpired method expects an Observable from getRefreshToken(), but since you tried using subscribe inside getRefreshToken(), it no longer returns an Observable, which leads to the error.
private handleTokenExpired(
req: HttpRequest<any>,
next: HttpHandler,
): Observable<HttpEvent<any>> {
return this.authService.getRefreshToken().pipe(
switchMap((authResponse) => {
const newAccessToken: string = authResponse.accessToken;
const newRefreshToken: string = authResponse.refreshToken;
// Optionally store tokens in local storage
this.storage.set('access_token', newAccessToken);
this.storage.set('refresh_token', newRefreshToken);
// Clone the original request with the new token
const clonedRequest = this.addToken(req, newAccessToken, newRefreshToken);
// Continue with the modified request
return next.handle(clonedRequest);
}),
catchError((error) => {
console.error('Error handling expired access token:', error);
return throwError(error);
})
);
}
1