I've had a need to do something similar where language and API key are loaded in dynamically.
To do this, I've created a class called AppInitService. Here, I'll initialise various properties in my app on the fly, such as translation language/currency or, in the case of AGM, the API key and language.
In your app.module.ts
or whatever you use you would add the following provider:
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AgmCoreModule, LazyMapsAPILoaderConfigLiteral, LAZY_MAPS_API_CONFIG } from '@agm/core';
@NgModule({
imports: [
AgmCoreModule.forRoot({
// The apiKey must always be set, even if empty.
apiKey: 'MyApiKey'
})
],
providers: [
{
// APP_INITIALIZER is the Angular dependency injection token.
provide: APP_INITIALIZER,
// Pass in the AGM dependency injection token.
deps: [LAZY_MAPS_API_CONFIG],
// Allow for multiple startup injectors if needed.
multi: true,
// UseFactory provides Angular with the function to invoke.
useFactory: (googleMapsConfig: LazyMapsAPILoaderConfigLiteral) => () => AppInitService.Init(googleMapsConfig)
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
Then in AppInitService.ts
:
import { Injectable } from '@angular/core';
import { LazyMapsAPILoaderConfigLiteral } from '@agm/core';
@Injectable()
export class AppInitService {
public static Init(googleMapsConfig: LazyMapsAPILoaderConfigLiteral) : Promise<void> {
return new Promise<void>((resolve, reject) => {
// Here you'll put in your call to retrieve your language code.
const languageCode = GetMyLanguageCode();
// And now we set it.
googleMapsConfig.language = languageCode;
// Resolve the promise as we're done.
resolve();
});
}
}
There's an example of how to use the Angular app initialisation here. I prefer static functions though as you don't have to instantiate the class in order to use them.