【问题标题】:Angular module created twice using forChildAngular 模块使用 forChild 创建了两次
【发布时间】:2021-02-02 23:00:52
【问题描述】:

我有一个模块,LoginModule,需要为其提供一些配置,因此它提供了 forRoot。 我在我的 AppModule 中使用了这个 forRoot()。 现在我有另一个模块 Module2,它本身是由 AppModule 导入的。我需要Module2中LoginModule的一个组件,所以Module2需要导入LoginModule。但是它应该怎么做呢?

似乎无论我做什么,LoginModule 构造函数都会被调用两次,如果 Module2 导入 LoginModule:一次是通过 AppModule 中的 forRoot(),一次用于在 Module2 中导入。 我尝试在 Module2 中使用 forChild 模式进行导入,但这并没有改变任何东西。 由于我想在创建 LoginModule 时运行一些初始化代码,因此我设置了如下所示的解决方案来检测 LoginModule 是否是根模块。

我的印象是,当使用 forChild 之类的东西时,根本不应该有第二个 LoginModule。我错了吗?还是我犯了一个错误,导致第二个 LoginModule 不应该存在?

@NgModule({
    declarations: [
// some things are declared
    ],
    imports: [
// various imports
    ],
    exports: [
// some exported components exist
    ]
})
export class LoginModule {
// forRoot is used to inject a configuration into the module
// LoginModule.forRoot() is used in the AppModule of my app.
    static forRoot(config: UserSystemConfig): ModuleWithProviders<LoginModule> {
        return {
            ngModule: LoginModule,
            providers: [
                LoginService,
                LoginAuthGuard, 
                {
                    provide: libConf, // an injection token
                    useValue: config
                },
                {
                    provide: mKey, // an injection token
                    useValue: true
                }
            ],
        }
    }
// forChild skips providing anything but the key that I use to know if this is the root instance.
    static forChild(): ModuleWithProviders<LoginModule> {
        return {
            ngModule: LoginModule,
            providers: [{
                provide: mKey,
                useValue: false
            }]
        }
    }

    constructor(@Inject(mKey) isRoot: boolean) {
        if (isRoot) {
// Run initialization for the module only in root module.
        }
    }
}
}

【问题讨论】:

    标签: angular angular11


    【解决方案1】:

    forRoot()forChild() 帮助您管理服务。它与模块的代码是否执行无关。每次使用时都会执行。如果不执行就没有意义了。

    当你使用forRoot() 并且如果模块是延迟加载的(使用它自己的注入器),它的提供者将是根注入器中提供者的相同实例。否则模块将实例化它自己的提供者实例。

    【讨论】:

      猜你喜欢
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 2017-10-21
      • 1970-01-01
      • 2019-04-08
      相关资源
      最近更新 更多