I’m encountering an issue with an Angular HTTP interceptor that doesn’t seem to be triggering or modifying HTTP requests as expected. Here’s a summary of the problem and the setup I’ve tried:
Problem Description:
I have implemented an HTTP interceptor in my Angular application to add an Authorization header to outgoing HTTP requests. However, the interceptor is not triggering, and the header is not being added. Additionally, console logs within the interceptor are not appearing in the browser console.
this is my app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideClientHydration } from '@angular/platform-browser';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { provideHttpClient } from '@angular/common/http';
import { AuthInterceptor } from './Services/auth.interceptor';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers:[
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(),
provideAnimationsAsync(),
provideHttpClient(),
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}]
};
auth.intercepter.ts
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { LoginserviceService } from "./loginservice.service";
@Injectable()
export class AuthInterceptor implements HttpInterceptor
{
constructor(private loginservice:LoginserviceService)
{
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let newreq=req;
let token=this.loginservice.getToken();
console.log("interceptor:"+token);
if(token!=null)
{
newreq=newreq.clone({setHeaders:{Authorization:`Bearer ${token}`}})
}
return next.handle(newreq);
}
}
Himanshu Maurya is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
You need to use withInterceptorsFromDi()
:
provideHttpClient(withInterceptorsFromDi()),
Either add withInterceptorsFromDi
provideHttpClient(withInterceptorsFromDi()),
{ provide: HTTP_INTERCEPTORS, useClass: AuthIInterceptor, multi: true },
or convert your Interceptor to a functional interceptor
provideHttpClient(withInterceptors([authInterceptor]))