Angular v16 独立组件无法与拦截器一起使用?

问题描述 投票:0回答:1

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 拦截器在子模块中不起作用

拦截器不拦截http请求(Angular 6)

app.module 中声明的拦截器不会拦截来自一个延迟加载模块的调用

Angular - 拦截器未在延迟加载的模块中加载

更新 控制台打印 if

  • 将拦截器的注册移至根app.module.ts
  • 将 @Injectable() 替换为 @Injectable({providedIn: 'root'})
angular interceptor angular-http-interceptors
1个回答
0
投票

想出:

    如果需要,
  1. HttpClientModule
    可以位于app.module中,并且可以延迟加载子模块。

  2. 确保该子模块中使用的所有服务类都已在此处注册。这就是我错过的地方。添加

    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },

  3. 独立组件,添加

    从 '@angular/common/http' 导入 { HTTP_INTERCEPTORS }; 从 'src/app/services/...' 导入 { ... } ; 从 './guards/auth.interceptor' 导入 { AuthInterceptor }; 提供商:[{
    提供:HTTP_INTERCEPTORS,
    useClass:AuthInterceptor,
    多:真实
    }],

© www.soinside.com 2019 - 2024. All rights reserved.