After creating my AuthInterceptor to handle 401 errors by requesting a new token, I encountered a problem. The handle401Error method is supposed to wait for other HTTP requests until the new token is received, but it isn't waiting as expected. Even though it successfully retrieves a new access token through an HTTP call, it doesn't pause until the refresh token is obtained. Please refer to the attached screenshot for more details.
https://i.sstatic.net/CdJlN.png
Interceptor.ts
isRefreshingToken = false;
tokenSubject: BehaviorSubject<string | null> = new BehaviorSubject<string | null>(null);
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
const timeOut = appSettings.ajaxTimeout;
const retryCount = appSettings.retryCount;
const retryDelay = appSettings.retryDelayMS;
return next.handle(request).pipe(
timeout(timeOut),
catchError((error) => {
if (error instanceof HttpErrorResponse) {
const httpErrorCode: number = error['status'];
switch (httpErrorCode) {
case StatusCodes.BAD_REQUEST:
return throwError(error);
case StatusCodes.UNAUTHORIZED:
return this.handle401Error(request, next);
default:
this._toastr.error(
'Sorry! something went wrong.',
'Error!'
);
return throwError(error);
}
} else {
return throwError(error);
}
}),
retryWhen((errors) => {
return errors.pipe(
concatMap((error, count) => {
if (count < retryCount) {
return of(error);
}
return throwError(error);
}),
delay(retryDelay)
);
})
);
}
// Rest of the code follows...