Angular 在惰性加载模块中使用服务

Angular use service in lazy loaded module

我有一个名为 routing.service 的服务,它订阅路由事件,当参数更改时,它会更新翻译服务。在构造函数中如下:

this.router.events.subscribe(val => {
    if (val instanceof ActivationEnd ) {
        let myVal = val.snapshot.params.lang;
        this.currentLang = myVal;
        this.translate.use(myVal);
        this.translate.setDefaultLang(config.defaultLang);
    }
});

我有一个导入到应用程序模块中的共享模块。在共享组件中一切正常:

<div [innerHTML]="'HOME.TITLE' | translate"></div>

但是在我的延迟加载模块中不起作用。即使我无法访问 subscribe 中的 this.currentLang。有什么想法吗?

更新: 这里是关于我的代码的更多细节:

app.module:

imports:[
  CommonModule,
  BrowserModule,
  FormsModule,
  NgtUniversalModule,
  TransferHttpCacheModule,
  HttpClientModule,
  AppRoutingModule,
  SharedModule
],

shared.module:

imports: [
  CommonModule,
  RouterModule,
  TranslateModule.forRoot({
    loader: {
      provide: TranslateLoader,
      useClass: TranslateUniversalLoader,
    }
  })
],
exports: [
  HeaderComponent,
  TranslateModule
]

懒-loaded.module:

imports: [
  CommonModule,
  FormsModule,
  CustomersRoutingModule,
  SharedModule,
],

我的app.component:

<!-- This is component of my shared.module and translation works fine here, but not in lazy loaded modules -->
<saz-header></saz-header> 
<router-outlet></router-outlet>

我刚刚忘记将提供程序添加到我的 SharedModule,如下所示:

providers: [
  RoutingService
]

很高兴你成功了,但为了完成:

1) 仔细检查您的服务是在哪个模块中提供的。一般来说,路由服务应该总是可以访问的,并且加载你的 AppModule 是有意义的,或者取决于你是否遵循 John Papa 建议的项目结构,一个 CoreModule。

在您的情况下,在 AppRoutingModule 中导入服务可能是合乎逻辑的。

2) 如果你确实有一个你想要延迟加载的服务,将所述服务包含在一个孤立的、简单的模块中可能是有益的,你可以在需要时延迟加载它(简单地说,一个只包含您可能需要或不需要的一些东西的小模块)