2

So, I've 3 modules in my Angular app.

// main module
@NgModule({
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

// lazy loading module
@NgModule({
})
export class ClinicModule { }

// lazy loading module
@NgModule({  
})
export class PatientModule { }

we know, for lazyloading behavior purposes, I cant import ClinicModule and PatientModule in my AppModule.

But, there is a service inside of ClinicModule called PatientGroupService.

I use this service in ClinicModule for CRUD operations and in PatientModule to bring the PatientGroup List.

So, I need it in both module, the only way, I found, to get only one instance of PatientGroupService without import ClinicModule in AppModule was provide PatientGroupService directly on AppModule, like this

// main module
@NgModule({
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers :[PatientGroupService]
})
export class AppModule { }

You may noticed, it is not a "global service", only a service used for 2 non main modules.

It works, but I wanna know:

  • Is this the "correct way" to achieve my goal?
  • Is there another/better way to do that?
Jonathan
  • 39
  • 6
  • why not provide this service in `ClinicModule` and `PatientModule` only? – Max Koretskyi Aug 11 '17 at 11:55
  • First of all, Thanks for reply Maximus !! .. At this particular case, there is no problem, I dont need only one instance( In fact, It would make it modules more auto sufficient). But, Should not I try to keep only one instance whenever I can? It would have better performance? Asides, if I realy need only one instance, is this aproach acceptable? – Jonathan Aug 11 '17 at 13:41
  • 1
    there's almost no difference between one and two instances) so I would go with two instances since it provides encapsulation - you don't really need an application wide visibility. But if you really need only once instance, you should provide the service in AppModule only – Max Koretskyi Aug 11 '17 at 14:27
  • 1
    Thanks Max !! .. You have made my day!! – Jonathan Aug 11 '17 at 17:59
  • you're welcome buddy, good luck! – Max Koretskyi Aug 11 '17 at 18:07
  • And if you rly need a single instance of the service, you can create an instance at the root module and share this instance between lazy-loaded modules. @see https://angular-2-training-book.rangle.io/handout/modules/shared-di-tree.html – Braincompiler Aug 14 '17 at 07:13
  • Yes VuuRWerK, that is what I did using the 'forRoot()' Pattern!!! Thanks again! – Jonathan Aug 15 '17 at 01:26

0 Answers0