Recently I needed to have client side settings in an Angular app. My app had to call some 3rd party webservices and their location was different per environment (test, QA and production), I also had to configure a couple of parameters that were necessary when calling them.
There’s support for this in Angular using “environments”. If you scaffold a new Angular app with angular-cli you’ll get a folder “Environments”.
These files can be used while building the application. Specifying the environment will bundle the environment specific file together with the rest of your application. Which is great but I don’t want to rebuild the application when I go from test to QA and finally to production. Typically settings are changed when deploying to an environment, at least that’s what I usually do with my .NET projects.
Trying to have one unified way of handling the settings gives two challenges: how to bootstrap the Angular app with dynamic settings and how to manage these during deployment.
I added a client-config.json file in my asset folder to contain all the settings and the values which were correct during development.
This file needs to be downloaded before most of the application actually starts so I added a settings provider.
import { Http } from '@angular/http'; import { Injectable } from '@angular/core'; @Injectable() export class SettingsProvider { private config : any; constructor(private http: Http) { } public loadConfig() : Promise<any>{ return this.http.get("assets/client-config.json") .map(res => res.json()) .toPromise() .then(settings => this.config = settings); } public get configuration(): any { return this.config; } } |
Then in my app.module.ts I add a new function to load the configuration.
export function init(settingsProvider: SettingsProvider) { return () => settingsProvider.loadConfig(); } |
I also changed the NgModule declaration to include
providers: [{ 'provide': APP_INITIALIZER, 'useFactory': init, 'deps': [SettingsProvider], 'multi': true }, SettingsProvider] |
The crux here is the APP_INITIALIZER token which Angular provides to run logic before the application starts. You can read more about it here and here.
With the client side now done, the application still needs to get the correct values when the application is pushed to different environments. This is the easy part as VSTS has support for file transforms and variable substitution. I just add my client-config.json to the list of files that need to be changed. VSTS will replace any variable it finds that can be matched with variables defined for the environment where I deploy.
The client-config.json is also added to the list of files the Angular build needs to pick up.
"apps": [ { "root": "src", "outDir": "../wwwroot", "assets": [ "assets", "favicon.ico", "client-config.json" ], .... }] |
The end result is a single way to manage environment specific settings for my .NET Core and Angular applications.