Runtime configuration loading in Angular
https://medium.com/@gmurop/managing-dependencies-among-app-initializers-in-angular-652be4afce6f
config.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppConfig } from '../model/config.model';
const CONFIG_PATH = '/assets/config.json';
@Injectable()
export class ConfigurationService {
private appConfig: AppConfig;
constructor(private http: HttpClient) {}
public async loadAppConfig(configPath: string = CONFIG_PATH) {
return this.http
.get(configPath)
.toPromise()
.then((data: AppConfig) => {
this.appConfig = data;
});
}
public get(key: string): any {
if (!this.appConfig) {
throw Error('Config file not loaded!');
}
return this.appConfig[key];
}
public set(key: string, value: any) {
this.appConfig[key] = value;
}
}
config.model.ts
export interface AppConfig {
apiEndpoint: string;
}
config.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ConfigurationService } from './service/config.service';
@NgModule({
declarations: [],
providers: [ConfigurationService],
imports: [CommonModule],
})
export class ConfigModule {}
Your core/app module where you want to load the configuration
imports: [
...,
ConfigModule,
],
providers: [
...,
{
provide: APP_INITIALIZER,
multi: true,
deps: [ConfigurationService],
useFactory: (configurationService: ConfigurationService) => {
return () => {
return configurationService.loadAppConfig('/assets/config.json');
};
},
},
],