In my app I need to use ng-intercom
https://github.com/CaliStyle/ng-intercom, which requires a config key to be set in forRoot()
method.
The config key is loaded from an API call, done in main.ts
. The config is fetched from API, then set to APP_CONFIG
in AppConfigService
and then the app is bootstrapped.
main.ts
const appConfigRequest = new XMLHttpRequest();
appConfigRequest.addEventListener('load', onAppConfigLoad);
appConfigRequest.open('GET', 'https://api.myjson.com/bins/lf0ns');
appConfigRequest.send();
// Callback executed when app config JSON file has been loaded.
function onAppConfigLoad() {
const config = JSON.parse(this.responseText);
initConfig(config);
}
// Sets fetched config to AppConfigService constant APP_CONFIG and calls bootstrap()
function initConfig(config) {
const injector = ReflectiveInjector.resolveAndCreate([AppConfigService]);
const configService = injector.get(AppConfigService);
configService.set(config);
bootstrap();
}
function bootstrap() {
platformBrowserDynamic().bootstrapModule(AppModule).then().catch(err => console.error(err));
}
app-config.service.ts
import { Injectable } from '@angular/core';
export let APP_CONFIG: any = {};
@Injectable()
export class AppConfigService {
constructor() {}
public set(config) {
APP_CONFIG = Object.assign(config);
}
}
In AppModule
I import the APP_CONFIG
and use the key from the config in the forRoot()
of the IntercomModule
:
app.module.ts
import { NgModule, InjectionToken, Inject, APP_INITIALIZER } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { APP_CONFIG } from './../shared/services/app-config.service';
import { IntercomModule } from 'ng-intercom';
@NgModule({
imports: [
BrowserModule,
FormsModule,
IntercomModule.forRoot({
appId : APP_CONFIG.intercomKey,
updateOnRouterChange: false
})
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Config example:
{
"production": true,
"envName": "staging",
"apiBaseURL": "//api.staging.site.com/v1/",
"intercomKey": "qz0b98qo"
}
The problem: when the IntercomModule is initialized, the config key is undefined APP_CONFIG.intercomKey
, because the config has not been fetched from API yet.
How do I make sure the config is available when the modules are initialized? Any ideas?
I have tried calling a function in the forRoot()
method before but got an error Function calls are not supported in decorators
when compiling the app with AOT
See also stackblitz: https://stackblitz.com/edit/angular6-intercom-issue
See Question&Answers more detail:
os