任何人都可以向我澄清如何使用.forRoot()调用来构建多个嵌套功能模块层次结构?
例如,如果我有这样的模块怎么办?
- - MainModule
- - SharedModule
- - FeatureModuleA
- - FeatureModuleA1
- - FeatureModuleA2
- - FeatureModuleB
如何定义FeatureModuleA以某种方式“传送”.forRoot()函数?
- @NgModule({
- imports: [
- //- I can use .forRoot() calls here but this module not the root module
- //- I don't need to import sub-modules here,FeatureA only a wrapper
- //FeatureModuleA1.forRoot(),//WRONG!
- //FeatureModuleA2.forRoot(),//WRONG!
- ],exports: [
- //I cannot use .forRoot() calls here
- FeatureModuleA1,FeatureModuleA2
- ]
- })
- class FeatureModuleA {
- static forRoot(): ModuleWithProviders {
- return {
- //At this point I can set any other class than FeatureModuleA for root
- //So lets create a FeatureRootModuleA class: see below!
- ngModule: FeatureModuleA //should be: FeatureRootModuleA
- };
- }
- }
我可以为root用户创建另一个类,然后将其设置在FeatureModuleA的forRoot()函数中:
- @NgModule({
- imports: [
- //Still don't need any sub module within this feature module
- ]
- exports: [
- //Still cannot use .forRoot() calls but still need to export them for root module too:
- FeatureModuleA1,FeatureModuleA2
- ]
- })
- class FeatureRootModuleA { }
But how can I “transfer” .forRoot() calls within this special@H_301_17@ ModuleClass?
如我所见,我需要将所有子模块直接导入到我的根MainModule中,并为每个子模块调用.forRoot():
- @NgModule({
- imports: [
- FeatureModuleA1.forRoot(),FeatureModuleA2.forRoot(),FeatureModuleA.forRoot(),SharedModule.forRoot()
- ]
- })
- class MainModule { }
我对吗?在你回答之前,请看看这个文件:@H_301_17@https://github.com/angular/material2/blob/master/src/lib/module.ts
正如我所知道的那样,由官方的角色队维持这个回购.所以他们通过在特殊的MaterialRootModule模块中导入所有的.forRoot()调用来解决上述问题.我真的不明白如何应用于我自己的根模块?根和.forRoot在这里真的意味着什么?是否相对于包,而不是实际的Web项目?
通常forRoot用于添加应用程序/单例服务.
- @NgModule({
- providers: [ /* DONT ADD HERE */ ]
- })
- class SharedModule {
- static forRoot() {
- return {
- ngModule: SharedModule,providers: [ AuthService ]
- }
- }
- }
推理是,如果您将AuthService添加到@NgModule中的提供程序,则如果将SharedModule导入其他模块,则可以创建多个.
当将SharedModule导入到热键加载的模块中时,是否创建该服务,但是所提及的文档是关于延迟加载的模块的说明,我并不完全清楚.当您懒惰加载模块时,所有的提供程序都将被创建.
因此,我们添加一个(通过惯例)forRoot方法来表示该方法只应该被调用为根(app)模块,而对于其他模块,它应该只是被正确导入
- @NgModule({
- imports: [SharedModule]
- })
- class FeatureModule {}
- @NgModule({
- imports: [SharedModule.forRoot()]
- })
- class AppModule {}