Angular 版本 16,MoneyComponent 是一个独立组件。
应用程序结构是 src pp\pages\money.只有一页
moneyForms
需要拦截器向 API HttpPost 发送附加信息,因此不是将拦截器添加到 app.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 {}
预期的信息没有添加到标头中,所以我将 AuthInterceptor 简化为
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);
}
}
控制台仍然没有打印 --- 你好 ----。
我已经检查了这些帖子,确保
HttpClientModule
仅加载一次,并且位于 root app.module.ts
中。
Angular2 Http 拦截器在子模块中不起作用
app.module 中声明的拦截器不会拦截来自一个延迟加载模块的调用
更新 控制台打印 if
想出:
HttpClientModule
可以位于app.module中,并且可以延迟加载子模块。
确保该子模块中使用的所有服务类都已在此处注册。这就是我错过的地方。添加
{
提供:HTTP_INTERCEPTORS,
useClass:AuthInterceptor,
多:真实
},
独立组件,
从 '@angular/common/http' 导入 { HTTP_INTERCEPTORS };
从 'src/app/services/...' 导入 { ... } ;
从 './guards/auth.interceptor' 导入 { AuthInterceptor };
提供商:[{
提供:HTTP_INTERCEPTORS,
useClass:AuthInterceptor,
多:真实
}],