Angel版本16,MoneyComponent是一个独立的组件.
应用程序 struct 是
SRC\APP\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);
}
}
仍然,控制台没有打印--- Hello ----.
我判断了这些帖子,确保HttpClientModule
只加载了一次,并且位于根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个 如果出现以下情况,控制台将打印
- 将拦截器的注册移动到根app.mode.ts
- 将@Inputable()替换为@Injectable({ProvidedIn:‘Root’})