Angular5: Deploying Angular application to multiple clients

What you can do it host the config file in json format in the assets folder and retrieve it dynamically. You need to make sure that you retrieve it before the app starts, that way it can be available in components/services when they need it. For that, you can use the APP_INITIALIZER Token

Step #1: put your json configuration files under src/assets/config/conf.json (json format, not ts format since there is no TS compiler in prod mode)

Step #2: Add a new config service

import {Inject, Injectable} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from 'rxjs/Rx';
import {environment} from "../../environments/environment";

/**
 * Declaration of config class
 */
export class AppConfig
{
//Your properties here
  readonly apiEndpoint: string;
}

/**
 * Global variable containing actual config to use. Initialised via ajax call
 */
export let APP_CONFIG: AppConfig;

/**
 * Service in charge of dynamically initialising configuration
 */
@Injectable()
export class AppConfigService
{

  constructor(private http: HttpClient)
  {
  }

  public load()
  {
    return new Promise((resolve, reject) => {

      this.http.get('/assets/config/config.json').catch((error: any): any => {
        reject(true);
        return Observable.throw('Server error');
      }).subscribe((envResponse :any) => {
        let t = new AppConfig();
        //Modify envResponse here if needed (e.g. to ajust parameters for https,...)
        APP_CONFIG = Object.assign(t, envResponse);
        resolve(true);
      });

    });
  }
}

Step #3: In your main module, add this before declaring the module

/**
* Exported function so that it works with AOT
* @param {AppConfigService} configService
* @returns {Function}
*/
export function loadConfigService(configService: AppConfigService): Function 

{
  return () => { return configService.load() }; 
}

Step #4: Modify the module providers to add this

providers: [
  …

  AppConfigService,
  { provide: APP_INITIALIZER, useFactory: loadConfigService , deps: [AppConfigService], multi: true },


],

Step 5: In your code, use the config

import {APP_CONFIG} from "../services/app-config.service";

//…
return APP_CONFIG.configXXX;

Now, you can ship the app to multiple clients; each client just need to have theyr specific parameter in conf.json file

Leave a Comment