Angular version 16, MoneyComponent is a standalone component.
Application structure is
src\app\pages\money. Only one page moneyForms needs interceptor to send in additional info to API HttpPost, so instead of adding the interceptor into app.module, it's added to a sub lazy load module, money.module.ts:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { moneyFormsComponent } from './money-forms.component';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from '../../guards/auth.interceptor';
@NgModule({
declarations: [
moneyFormsComponent
],
imports: [
CommonModule,
RouterModule.forChild([
{
path:'',
component:moneyFormsComponent,
children: [
{ path: 'money-forms', loadComponent: () => import('../m/m.component').then(t => t.MoneyComponent)},
...
]
}
]),
],
providers:[
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
},
],
exports: [RouterModule]
})
export class moneyFormsModule {}
Expected info is not adding into header, so I simplified the AuthInterceptor as
import { HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
console.log("--- Hello ----");
return next.handle(request);
}
}
Still console has no --- Hello ---- printed.
I've checked these posts, made sure HttpClientModule is only loaded once, and is in root app.module.ts.
Angular2 Http Interceptor not working in child module
Interceptor not intercepting http requests (Angular 6)
Interceptor declared in app.module is not intercepting call from one lazy loaded module
Angular - Interceptor not loading in a lazy loaded module
Update Console prints if
- Move registration of interceptor to root app.module.ts
- Replace @Injectable() with @Injectable({ providedIn: 'root'})
Figured out:
HttpClientModulecan be in root app.module if needed i.e. used by root components, etc., and can be in a lazy load sub-modules too.Make sure all service, factory etc. used in this sub-module are registered here, this is where I missed. Then add
Standalone component, add