Dynamically load configuration file before app start : Angular

Priti Jha
1 min readMar 15, 2023

--

In an Angular application, you can dynamically load a configuration file before the application starts using the APP_INITIALIZER provider. This is useful when you want to load configuration data from a backend service or a file at runtime.

Here are the steps to dynamically load a configuration file before the app starts in Angular:

  1. Create a configuration file in JSON format with the necessary data. For example, config.json.
  2. Create a service to load the configuration data. For example, ConfigService.
  3. In the ConfigService, import the HttpBackend and inject it into the constructor:

below code of configService.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';

@Injectable({
providedIn: 'root',
})
export class ConfigLoaderService {
private httpClient: HttpClient;
private configs: Configs;
constructor(handler: HttpBackend) {
this.httpClient = new HttpClient(handler);
}

get getConfigDetails(): any {
if (!this.configs) {
throw Error('Config file not loaded!');
}
return this.configs;
}

public async loadConfigs(): Promise<any> {
return this.httpClient.get('assets/configs.json').pipe((settings) => settings).toPromise().then((settings) => {
this.configs = settings as Configs;
});
}
}

export interface Configs{
AppId: string;
ApiBaseURL: string;
AWS_ACCESS_KEY_ID: string;
AWS_SECRET_ACCESS_KEY: string;
AWS_region: string;
AWS_secretId: string;
}

--

--

Priti Jha
Priti Jha

Written by Priti Jha

Senior front-end developer writing about Angular 8 , Ionic Framework ,Javascript, HTML, Css and all front end technology.