简体   繁体   English

延迟加载模块中的角度使用服务

[英]Angular use service in lazy loaded module

I have a service called routing.service which subscribes to routing event and when a parameter changes, it updates Translate service. 我有一个名为routing.service的服务,该服务订阅路由事件,并且当参数更改时,它会更新翻译服务。 As following in constructor: 在构造函数中如下所示:

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);
    }
});

I have a shared module that is imported into the app module. 我有一个导入到应用程序模块中的共享模块。 In shared component everything works fine: 在共享组件中,一切正常:

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

But in my lazy loaded modules not working. 但是在我的懒加载模块中不起作用。 Even I can't access to this.currentLang that is inside subscribe . 即使我不能访问this.currentLang是内部subscribe Any idea? 任何想法?

Update: Here is more detail about my code: 更新:这是有关我的代码的更多详细信息:

app.module: app.module:

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

shared.module: shared.module:

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

lazy-loaded.module: 懒惰loaded.module:

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

My app.component: 我的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>

Glad you got it working, but for sake of completion: 很高兴您能正常使用,但为了完成:

1) Double check in which module your service is provided. 1)仔细检查您提供的服务模块。 Generally, a routing service should always be accessible, and it makes sense to load with your AppModule, or depending on if you follow John Papa's suggested project structure, a CoreModule. 通常,路由服务应始终可访问,并且可以通过AppModule加载或根据您是否遵循John Papa建议的项目结构CoreModule进行加载。

In your case, it might be logical to have the service imported in the AppRoutingModule. 在您的情况下,将服务导入AppRoutingModule中可能是合乎逻辑的。

2) If you do have a service that you'd like lazy loaded, it might be beneficial to include said service in an isolated, simple module that you can lazy load whenever you need it to (simply put, a small Module that just includes the few things you may or may not need) 2)如果您确实有一个需要延迟加载的服务,则最好将该服务包含在一个隔离的简单模块中,以便您可以在需要时进行延迟加载(简单地说,就是一个包含以下内容的小模块:您可能需要或不需要的一些东西)

I had just forgotten to add the provider to my SharedModule as following: 我刚刚忘记将提供程序添加到我的SharedModule中,如下所示:

providers: [
  RoutingService
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM