【发布时间】:2021-10-22 04:17:45
【问题描述】:
我有一个使用AgmCoreModule 的模块。它将apiKey 应用于forRoot 并通过LAZY_MAPS_API_CONFIG 添加AgmCoreModule:
...some_module.ts
export const AgmCoreModuleForRoot = AgmCoreModule.forRoot()
imports: [
AgmCoreModuleForRoot,
]
providers: [
{
provide: LAZY_MAPS_API_CONFIG,
useClass: GoogleMapsConfigService,
deps: [GoogleMapsConfigServiceConfig],
},
],
export class SomeModule {
static forRoot(
config?: GoogleMapsConfigServiceConfig,
): ModuleWithProviders<SomeModule> {
return {
ngModule: SomeModule,
providers: [{ provide: GoogleMapsConfigServiceConfig, useValue: config }],
};
}
}
该模块主要由不需要AgmCoreModule 的组件组成,因此SomeModule 可以使用空白forRoot 导入,例如SomeModule.forRoot()。
但是,我在使用 SomeModule 和在更高模块中导入了 AgmCoreModule 的应用程序时遇到了问题,例如 App.module。这会覆盖AgmCoreModule 的forRoot。
示例:
...app.module
imports:[
AgmCoreModule.forRoot({
apiKey: environment.googleApiKey,
libraries: ['places'],
}),
...downstream.module.ts
imports: [
SomeModule.forRoot() <-- This overwrites the above apiKey making the google places api not work
我希望能够灵活地根据SomeModule 的forRoot 中是否存在apiKey 来有条件地加载AgmCoreModule。
这甚至是一件事吗?
【问题讨论】:
-
你应该在每个应用程序中只使用一次 forRoot,最好是 AppModule 或 CoreModule 在其他情况下你只需要使用 SomeModule 而不调用 forRoot 的组件
-
SomeModule可以在任何地方加载。它必须有一个forRoot才能将该数据传递给 Google 地方模块。 -
嗯,你读过这个吗? angular-maps.com/api-docs/agm-core/modules/agmcoremodule "在根级别注册模块时请使用此方法。"你不需要在每个地方都使用 forRoot 你需要在根目录中使用 AgmCoreModule 通常 CoreModule 或 AppModule 在其他地方你使用该模块而不使用 forRoot
-
请停止尝试重写用例...这个模块是一个外部库,我不知道
AgmCoreModule是否被加载,在forRoot的存在之外在SomeModule