【问题标题】:How to import Angular HTTP interceptor only for Child module如何仅为子模块导入 Angular HTTP 拦截器
【发布时间】:2019-04-17 17:50:01
【问题描述】:

我已经在 AppModule 中导入了 HttpClientModule。

import { HttpClientModule } from '@angular/common/http';

export const AppRoutes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  {
    path: 'account',
    loadChildren: './auth/auth.module#AuthModule'
  },
  {
    path: 'dashboard',
    loadChildren: './content/content.module#ContentModule'
  }
];

一旦我启动站点,它将重定向到我添加了 http 拦截器的仪表板模块(延迟加载模块)。

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpInterceptorService } from '../services/http-interceptor.service';
@NgModule({
providers : [
      { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
    ]
})

但它不起作用。谁能帮帮我?

【问题讨论】:

  • 发布 appmodule ts

标签: angular http httpclient interceptor angular-http-interceptors


【解决方案1】:

Http 拦截器只是一个服务,在任何模块上注入它都不会有任何区别 - 只需在 AppModule 中做同样的事情,这将有助于你工作 - 如果你有同样的问题,你可以尝试注入像下面在你的共享模块上

实现这一点的常见模式不是直接在 @NgModule 声明中公开提供程序,而是在像这样的静态 forRoot 函数中公开提供程序:

export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
         { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true }
      ]
    };
  }
}

然后您可以在AppModule 上导入您的SharedModule,例如SharedModule.forRoot()

希望这可行 - 快乐编码

【讨论】:

  • 感谢您的努力。但实际上它会在一段时间后起作用。
  • 没问题 :) 编码愉快
猜你喜欢
  • 1970-01-01
  • 2018-05-04
  • 2018-07-08
  • 2023-03-13
  • 2016-12-10
  • 2017-11-07
  • 2018-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多