1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Interceptor not working in Angular 18 project

Discussão em 'Angular' iniciado por msabate, Outubro 11, 2024.

  1. msabate

    msabate Guest

    I'm trying to use my interceptor but is not working. The console log isnot shown so, I don't know why, my interceptor is not active.

    What i'm doing bad?

    auth.interceptor.ts

    import { HTTP_INTERCEPTORS, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
    import { Injectable } from "@angular/core";
    import { AuthService } from "./auth.service";
    import { Observable } from "rxjs";

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {

    constructor(private authService:AuthService) {

    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    var authReq = req;
    console.log("intercepting");
    const token = this.authService.getToken();
    if(token != null) {
    authReq = req.clone({
    headers: req.headers.set('Authorization', `Bearer ${token}`)
    });
    }
    return next.handle(authReq);
    }
    }

    export const authInterceptorProviders =
    {
    provide : HTTP_INTERCEPTORS,
    useClass : AuthInterceptor,
    multi : true
    }


    app.config.ts

    import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
    import { provideRouter } from '@angular/router';

    import { routes } from './app.routes';
    import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
    import { provideHttpClient, withInterceptors } from '@angular/common/http';
    import { authInterceptorProviders } from './services/auth/auth.interceptor';

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


    Thanks for your help!

    Continue reading...

Compartilhe esta Página