Vahid Najafi
Vahid Najafi

Reputation: 5263

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. 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. Any idea?

Update: Here is more detail about my code:

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
]

lazy-loaded.module:

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

My 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>

Upvotes: 0

Views: 2672

Answers (2)

jarodsmk
jarodsmk

Reputation: 2099

Glad you got it working, but for sake of completion:

1) Double check in which module your service is provided. 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.

In your case, it might be logical to have the service imported in the 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)

Upvotes: 1

Vahid Najafi
Vahid Najafi

Reputation: 5263

I had just forgotten to add the provider to my SharedModule as following:

providers: [
  RoutingService
]

Upvotes: 0

Related Questions