How can I provide a global service (eg providing data) and access it from the submodules in an angular 2+ app? Here the emphasis lies on sub-modules. I know it's pretty straight forward with a component hierarchy tree, but I couldn't find any good explanation how that works with multiple modules.
For example, if we have the following app structure/hierarchy:
AppModule
myservice
AppComponent
FeatureModule1
ComponentA
ComponentB
FeatureModule2
ComponentC
ComponentD
FeatureModule3
ComponentE
Where do I have to provide the service? Just in AppModule
or also in the submodules ( FeatureModule1
, FeatureModule2
and FeatureModule3
)? The same question about importing. To import and provide only on the root level doesn't work ( FeatureModule1
for example has no access to the provided myservice
instance as far I've experienced.) Do I have to do the re-importing (eventually re-providing) on every hierarchy level?
You have to implement forRoot() in the module where you defined your service or define it in your AppModule. Do not provide the service in multiple modules, because this will create multiple instances. My preferred way is to create a SharedModule which provide all shared services like this:
@NgModule({
imports: [ ... ]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [
MyService
]
};
}
}
In my AppModule I import it with forRoot():
@NgModule({
declarations: [ ... ],
imports: [
...
SharedModule.forRoot()
],
providers: [ ... ],
bootstrap: [AppComponent]
})
export class AppModule { }
And in all other modules, I just have to import it without foorRoot.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.