Angular 2+:向子模块提供全局服务的单个实例 [英] Angular 2+: providing a single instance of a global service to sub-modules
问题描述
我如何提供全局服务(例如,提供数据),并在2+角度的应用程序中从子模块访问它?这里重点放在子模块上.我知道使用组件层次结构树是相当简单的,但是我找不到很好的解释说明如何将其与多个模块一起使用.
How can I provide a global service (e.g. 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
我必须在哪里提供服务?只是在 AppModule
中还是子模块( FeatureModule1
, FeatureModule2
和 FeatureModule3
)中?关于导入的相同问题.仅在根级别上导入和提供是行不通的(例如,据我所知,例如 FeatureModule1
无法访问所提供的 myservice
实例.)我必须在每个层次结构级别上重新导入(最终重新提供)吗?
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?
推荐答案
您必须在定义服务的模块中实现forRoot()或在AppModule中对其进行定义.不要在多个模块中提供服务,因为这将创建多个实例.我的首选方法是创建一个SharedModule,它提供所有共享服务,如下所示:
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
]
};
}
}
在我的AppModule中,我使用forRoot()导入它:
In my AppModule I import it with forRoot():
@NgModule({
declarations: [ ... ],
imports: [
...
SharedModule.forRoot()
],
providers: [ ... ],
bootstrap: [AppComponent]
})
export class AppModule { }
在所有其他模块中,我只需要导入而无需foorRoot.
And in all other modules, I just have to import it without foorRoot.
这篇关于Angular 2+:向子模块提供全局服务的单个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!