Angular 模块使用 forChild 创建了两次

Angular module created twice using forChild

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

看来无论我做什么,如果Module2 导入LoginModule,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.
        }
    }
}
}

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

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