After implementing my AuthInterceptor, I am facing an issue where the handle401Error method does not receive any response when calling this.authService.refreshToken().pipe() upon encountering a 401 error.
AuthInterceptor Implementation
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap, switchMap } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
isRefreshingToken:boolean = false;
constructor(public authService: AuthService, private injector: Injector) {}
addToken(req: HttpRequest<any>, token: string): HttpRequest<any> {
return req.clone({ setHeaders: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
}})
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = this.addToken(request, this.authService.getToken())
return next.handle(request).pipe (
catchError((error: Error) => {
if(error instanceof HttpErrorResponse){
console.log('err', error);
switch(error.status) {
case 401:
this.handle401Error(request, next)
default:
return throwError(error);
}
} else {
return throwError(error);
}
})
);
}
handle401Error(request: HttpRequest<any>, next: HttpHandler){
console.log('handle 401');
if(!this.isRefreshingToken) {
this.isRefreshingToken = true;
return this.authService.refreshToken().pipe(
switchMap((newToken: string) => {
console.log('newToken', newToken)
if (newToken) {
return next.handle(this.addToken(request, newToken));
}
}),
catchError((error) => {
console.log('error', error)
return throwError(error)
}),
tap(data => console.log(data))
)
}
}
}
AuthService Refresh Token
refreshToken(): Observable<string> {
console.log('refreshToken');
let token = 'xxx-xxx-xx';
return of(token).pipe(delay(1000));
}