Where is the best place to call load()
You can call load function in the App module. Angular provides a way to achieve it. You can use APP_INITIALIZER. The provided functions are injected at application startup and executed during app initialisation. If any of these functions returns a Promise or an Observable, initialisation does not complete until the Promise is resolved or the Observable is completed.
function initializeApp(): Promise<any> {
return new Promise((resolve, reject) => {
// Do some asynchronous stuff
resolve();
});
}
@NgModule({
imports: [BrowserModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [{
provide: APP_INITIALIZER,
useFactory: () => initializeApp,
multi: true
}]
})
export class AppModule {}
How would I take that resolved MyConfig from Promise and
inject throughout my Angular app?
Now, this can be done in number of ways, but I would suggest to create a service at the root level to keep the data in one place then you can pass it to the store or save on localStorage whatever fits your case.
Config Service:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';
import { map } from 'rxjs/operator/map';
@Injectable()
export class AppConfigService {
private configData: any;
constructor(private http: HttpClient) {}
load() :Promise<any> {
const promise = this.http.get('URL').toPromise()
.then(data => {
return data;
});
return promise;
}
// once you get the data set it;
setConfigData (data) {
this.configData = data;
}
getConfigData (data) {
return this.configData;
}
}
In you App.module.ts :
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './services/app-config.service';
export function appInit(appConfigService: AppConfigService) {
return new Promise((resolve, reject) => {
// Do some asynchronous stuff
this.appConfigService.load().then(data=> {
this.appConfigService.setConfigData(data);
resolve();
})
});
}
@NgModule({
declarations: [
AppComponent
],
imports: [
],
providers: [AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInit,
multi: true,
deps: [AppConfigService]
}],
bootstrap: [AppComponent]
})
export class AppModule { }