Angular Interceptor - re-execute the same HTTP Interceptor after a catch

Discussão em 'Angular' iniciado por DanyBoy, Dezembro 27, 2024.

  1. DanyBoy

    DanyBoy Guest

    I'm looking for a solution to re-execute the same HTTP query after a catch is completed.

    For instance, as per below, I would like to re-execute the same call as the catch hanlded properly the re-authentication.

    See below:

    import { HttpContextToken, type HttpRequest, type HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
    import { inject } from '@angular/core';
    import { AuthService } from './auth.service';
    import { catchError, throwError } from 'rxjs';


    export const REFRESHER_TOKEN_INTERCEPTOR = new HttpContextToken(() => false)
    export const authInterceptor: HttpInterceptorFn = (req: HttpRequest<any>, next) => {

    const authService = inject(AuthService)
    const operationName = req.body.operationName.toLowerCase();
    const isRefresherToken = operationName.toLowerCase() === 'refreshtoken' ? true : false
    //By dafault, the interceptor will try to pass the JWT token but for the refresherToken we must pass the refresher token instead
    const jwtToken = authService.getToken(isRefresherToken)
    console.log(`JWTToken:${jwtToken}`)
    if (jwtToken) {
    const cloned = req.clone({
    setHeaders: {
    Authorization: `Bearer ${jwtToken}`
    }
    })
    return next(cloned).pipe(
    catchError((err: any) => {
    if (err instanceof HttpErrorResponse)
    switch (err.status) {
    case 401:
    authService.refreshToken()
    //I WOULD LIKE TO REEXECUTE THE SAME CALL HERE AS THE USER IS SUPPOSED TO BE IDENTIFIED AGAIN
    break;
    }
    return throwError(() => err)
    })
    )
    }
    return next(req);
    };

    Continue reading...

Compartilhe esta Página