0

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

8
  • You could try using async/await. Here is a good exemple how to use it. This should do the trick. Also consider using Angular's HttpClient instead of XMLHttpRequest. The HttpClient will wrap your request into promises what make it easy to work with async/await. You can see a guide here. Commented Sep 28, 2018 at 12:54
  • Thanks, will try that out. I was using XMLHttpRequest for IE11 support. Commented Sep 28, 2018 at 13:02
  • And it seems HttpClient can not be used in main.ts stackoverflow.com/questions/46681396/… Commented Sep 28, 2018 at 13:11
  • So since you will have to use XMLHttpRequest here is a good exemple on how to work with async/await and it. Commented Sep 28, 2018 at 13:14
  • Using promises does not seem to resolve my problem. Angular seems to create the AppModule (line 10) before hitting the code that does the request (line 36). See stackblitz.com/edit/… Commented Sep 28, 2018 at 13:28

2 Answers 2

1

The problem is that the code in app.module.ts is executed as soon as you import it in your main.ts. You have to dynamically import it to achieve your goal. I updated your example on Stackblitz to show a solution.

You might have to check out how TypeScript is transpiling dynamic imports, though. I'm not sure, if it is currently possible to target an ES version that is widely supported. See also the TypeScript docs on the topic here.

If it is possible to request and cache the app-config(s) on the server, that would be a cleaner solution, in my opinion.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I had to update my tsconfig.json with "module": "esNext" and "angularCompilerOptions": { "entryModule" : "./app/app.module#AppModule" } to avoid errors when compiling. It works now when serving in dev mode but when I compile for prod with AOT I get following error: "Unhandled Promise rejection: No NgModule metadata found for 'e'"
0

I had a similar problem, and @realhans' answer also broke AOT for me.

The solution mentioned here solves the issue while AOT keeps working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.