I have a module that uses AgmCoreModule. It takes the apiKey applied on the forRoot and adds it AgmCoreModule via LAZY_MAPS_API_CONFIG:
...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 }],
};
}
}
The module is mostly made of components that do not need AgmCoreModule so SomeModule can be imported with a blank forRoot like SomeModule.forRoot().
However, I'm running into issues using SomeModule with applications that have AgmCoreModule imported in a higher module say App.module. And that overrites the AgmCoreModule's forRoot.
example:
...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
I would like to have the flexibility to conditionally load the AgmCoreModule based on the existence of an apiKey in the forRoot of SomeModule.
Is this even a thing?
I cannot see your AgmCoreModule but have you tried doing something like the below to prevent reimporting the core modules?
// module-import.guard.ts
export function throwIfAlreadyLoaded(parentModule: any, moduleName: string) {
if (parentModule) {
throw new Error(`${moduleName} has already been loaded, import Core modules in the AppModule only.`);
}
}
// agm-core.module.ts
export class AgmCoreModule{
constructor(@Optional() @SkipSelf() parentModule: AgmCoreModule) {
throwIfAlreadyLoaded(parentModule, 'AgmCoreModule');
}
}
As for your api key overwriting situation, can you not just wrap it to return something else if the config is not there? Or does SomeModule need to communicate with GoogleMapsConfigService, if not then maybe something like the below might help you:
export class SomeModule {
static forRoot(config?: GoogleMapsConfigServiceConfig): ModuleWithProviders<SomeModule> {
if(config) {
return {
ngModule: SomeModule,
providers: [{ provide: GoogleMapsConfigServiceConfig, useValue: config }],
};
}
return {
ngModule: SomeModule
};
}
}