如何仅为子模块导入Angular HTTP拦截器 [英] How to import Angular HTTP interceptor only for Child module

查看:140
本文介绍了如何仅为子模块导入Angular HTTP拦截器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在AppModule中导入了HttpClientModule.

I have imported HttpClientModule in AppModule.

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拦截器的仪表板模块(延迟加载的模块).

Once I launch site, it will redirect to dashboard module(Lazy loaded module) where i added http interceptor.

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

但是它不起作用.谁能帮我吗?

But it doesn't working. Can anyone help me?

推荐答案

Http拦截器只是一项服务,将其注入任何模块不会有任何区别-只需在 AppModule 中进行相同操作这将有助于您的工作-如果遇到相同的问题,可以尝试在共享模块上进行如下注入

Http interceptor is just a service there won't be any difference in injecting it on any modules - just do the same in AppModule that will help you to work - if in case you have the same problem you can try injecting like below on your shared module

要实现的常见模式不是直接在 @NgModule 声明上公开提供程序,而是在诸如此类的静态forRoot函数中:

The common pattern to achieve that is not to expose providers directly on the @NgModule declaration but in a static forRoot function like that:

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

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

You can then import your SharedModule on AppModule like SharedModule.forRoot()

希望这行得通-编码愉快

Hope this works - Happy coding

这篇关于如何仅为子模块导入Angular HTTP拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆