Angular 18.0.5 not seeing the interceptor

Discussão em 'Angular' iniciado por EagleMind, Novembro 27, 2024.

  1. EagleMind

    EagleMind Guest

    Angular is not aknowledging the interceptor.

    So basically I executed

    ng generate interceptor JwtInterceptor


    and setup set it up to add the token to the header :

    import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
    import { catchError, throwError } from 'rxjs';

    export const jwtInterceptorInterceptor: HttpInterceptorFn = (req, next) => {
    console.log('Interceptor invoked');
    let token: string | null = localStorage.getItem("access_token");

    console.log("Token from localStorage:", token);
    if (token) {
    const clonedRequest = req.clone({
    headers: req.headers.set(
    'x-auth-token',token
    )
    });

    return next(clonedRequest).pipe(
    catchError((err: any) => {
    if (err instanceof HttpErrorResponse) {
    if (err.status === 401) {
    console.error('Unauthorized request:', err);
    } else {
    console.error('HTTP error:', err);
    }
    } else {
    console.error('An error occurred:', err);
    }

    return throwError(() => err);
    })
    );
    } else {
    console.log("no token")
    return next(req);
    }


    };


    Then added the interceptor in the provider :

    export const appConfig: ApplicationConfig = {
    providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(
    withInterceptors([jwtInterceptorInterceptor]),
    ),]
    };


    also tried the Di pattern in app.config.ts :

    export const appConfig: ApplicationConfig = {
    providers: [provideZoneChangeDetection({ eventCoalescing: true }), provideRouter(routes), provideHttpClient(withInterceptorsFromDi()), {
    provide: HTTP_INTERCEPTORS,
    useValue: jwtInterceptorInterceptor,
    multi: true

    },]
    };



    And i even put the provider inside the component as well which shouldn't be done as it might double trigger it or cause a conflict i'm assuming :

    @Component({
    selector: 'app-profile',
    standalone: true,
    imports: [ReactiveFormsModule],
    templateUrl: './profile.component.html',
    styleUrl: './profile.component.css',
    providers: [
    {
    provide: HTTP_INTERCEPTORS,
    useValue: jwtInterceptorInterceptor,
    multi: true
    }
    ],
    })


    I tried getting rid of all the interceptor's code and leaving only the loggings but still the interceptor is not being hit at all in any scenario : [​IMG]

    Note

    • This is the reference that seemed to me the most accurate to follow : text
    • I'm a week years old on angluar.
    • I went throught all stackoverflow issues

    Continue reading...

Compartilhe esta Página