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

emery
  • 137
  • 2
  • 8
  • You could try using `async/await`. [Here](https://javascript.info/async-await) 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](https://angular.io/guide/http). – ygorazevedo Sep 28 '18 at 12:54
  • Thanks, will try that out. I was using `XMLHttpRequest` for IE11 support. – emery Sep 28 '18 at 13:02
  • And it seems HttpClient can not be used in main.ts https://stackoverflow.com/questions/46681396/how-to-instantiate-http-service-in-main-ts-manually – emery Sep 28 '18 at 13:11
  • So since you will have to use `XMLHttpRequest` [here](https://stackoverflow.com/questions/48969495/in-javascript-how-do-i-should-i-use-async-await-with-xmlhttprequest) is a good exemple on how to work with `async/await` and it. – ygorazevedo Sep 28 '18 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 https://stackblitz.com/edit/angular6-intercom-issue-c4gc8h?file=src%2Fmain.ts – emery Sep 28 '18 at 13:28
  • You forgot to use `async/await`. See https://stackblitz.com/edit/angular6-intercom-issue-mmcjsj – ygorazevedo Sep 28 '18 at 14:52
  • I think I see what is going on here. Seens like `AppModule` is loaded before `main.ts` execute it's functions. – ygorazevedo Sep 28 '18 at 14:59
  • Exactly. Do you have any idea how to avoid this? – emery Sep 28 '18 at 15:44

2 Answers2

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.

realhans
  • 11
  • 1
  • 1
    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'" – emery Oct 01 '18 at 13:18
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.

Dennis Ameling
  • 707
  • 7
  • 15