Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

angular - Angular6 Using fetched config variable in module forRoot()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...