Reputation: 321
I'm trying to understand something about modules.
I have an AppModule (my root module) that contains a PageModule and a ServiceModule. The PageModule uses a service from ServiceModule (and future module will as well, but not the AppModule directly). I want that service to be a singleton, so I use the following code in the Service declaration:
@Injectable({
providedIn: 'root'
})
But I want my PageModule to explicitly depend on the ServiceModule so that future devs are aware that the PageModule has that dependency. Should I import the ServiceModule in PageModule, event though it basically does nothing? Should I import the ServiceModule in the root AppModule? Have I misunderstood something?
I should use providedIn: 'root'
in the ServiceModule (unless the module I'm using it in is LazyLoaded) and import the ServiceModule directly in PageModule without need to import it in AppModule. Am I right?
I hope the question is not redundant. I have tried to see other questions and read articles about Angular's dependency injection and modules, yet I do not understand if what I want is a bad practice or not.
Upvotes: 0
Views: 43
Reputation: 2795
you can define forRoot method in ServiceModule and provide another module description for AppModule. In such way AppModule can import your service module and initialize it, then PageModule and any other modules can explicitly import ServiceModule. a good overview link.
//ServiceModule.ts
@NgModule({
imports: [
CommonModule,
],
declarations: []
})
export class ServiceModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: ServiceModule,
providers: [
SingletoneService
]
};
}
constructor(
private singletoneService: SingletoneService,
) {
this.singletoneService.init();
}
}
//AppModule.ts
@NgModule({
declarations: [
AppComponent,
SvgDefinitionsComponent
],
imports: [
...
ServiceModule.forRoot(),
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
Upvotes: 2