Angular bietet die Möglichkeit Code zu laden bevor die eigentliche Anwendung bzw. Inhalte geladen werden. Dieser Code wird während der Initialisierung ausgeführt. Dadurch können u.a. Configs via Http-Calls geladen werden, deren Inhalte dann beim Start zur Verfügung stehen.
Genau dafür steht uns die Konstante APP_INITIALIZER zur Verfügung.
Um die Daten während der Initialiserung zu laden, benötigt man lediglich einen Service der in app.module.ts bei den Providern hinterlegt wird.
config.service.ts:
/** * Config service which is loaded right when the app is initialized. */ import { Injectable } from '@angular/core'; import {Http, Response} from "@angular/http"; @Injectable() export class ConfigService { private config: any; constructor(private http: Http){} load(): Promise<any>{ return this.http.get("http://loremipsum.com/config.json") .map( (response: Response) => response.json()) .toPromise() .then(data => { this.config = data; return data; }) } /** * Return the config. * * @param key * @return {any} */ getConfig() { return this.config; } }
Eintrag in den Providern in der app.module.ts:
NgModule({ providers: [ ConfigService, { provide: APP_INITIALIZER, useFactory: (configService: ConfigService) => function() {return configService.load()}, deps: [ConfigService], multi: true }] })
Zugriff auf den Service hat man, wie auf jeden anderen Service auch, durch Dependency Injection im Contructor.
Quelle: https://gillespie59.github.io/2016/12/04/angular2-code-before-rendering.html