Reputation: 306
I need some configuration data from my json file before any component or servise is rendered by the Angular 2 framework. I have not found any good working solution to achieve that.
I am using Angular 2 RC6 working in the mixed mode with Angular 1 so I am using upgrade adapter to perform bootstraping.
Have you got any ideas to achieve what I need?
Upvotes: 2
Views: 5300
Reputation: 6817
Check out this blog: https://www.cidean.com/blog/2019/initialize-data-before-angular-app-starts/
It uses APP_INITIALIZER
to hook AppConfigService
before app startup and fetch data. See the blog also for implementation of AppConfigService
.
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { AppConfigService } from './services/app-config.service';
export function appInit(appConfigService: AppConfigService) {
return () => appConfigService.load();
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
],
providers: [AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInit,
multi: true,
deps: [AppConfigService]
}],
bootstrap: [AppComponent]
})
export class AppModule { }
Upvotes: 2
Reputation: 306
In "main.ts" file I used the jQuery "$.getJSON" function to load the config file and on callback I call the bootstrap funtion:
declare var $: any;
declare var configFile: string;
import './polyfills.ts';
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { environment } from './environments/environment';
import { AppModule } from './app';
if (environment.production) {
enableProdMode();
this.configFile = 'assets/config.prod.json';
} else {
this.configFile = 'assets/config.json';
}
$.getJSON(this.configFile, (data) => {
environment.config = data;
platformBrowserDynamic().bootstrapModule(AppModule);
});
This way you can ensure bootstrapping is performed after your config data is fully loaded.
Upvotes: 0