Skip to content

Instantly share code, notes, and snippets.

  • Select an option

  • Save AndreasGassmann/07c89d4eece822eabb153d48d5045f39 to your computer and use it in GitHub Desktop.

Select an option

Save AndreasGassmann/07c89d4eece822eabb153d48d5045f39 to your computer and use it in GitHub Desktop.
Reading configuration files before application startup in Angular2 final release

In Your Module

import { APP_INITIALIZER } from '@angular/core';
import { AppConfig }       from './app.config';

@NgModule({
    ...
    providers: [
        AppConfig,
        { provide: APP_INITIALIZER, useFactory: (config: AppConfig) => () => config.load(), deps: [AppConfig], multi: true }
    ],
    ...
});

In app.config.ts

import { Inject, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class AppConfig {

    public static config: Object = null;
    public static env:    Object = null;

    constructor(private http: Http) {

    }

    public static get(key: any) {
        return AppConfig.config[key];
    }

    public static getEnv(key: any) {
        return AppConfig.env[key];
    }

    /**
     * This method:
     *   a) Loads "env.json" to get what is the current environment (e.g.: 'production', 'development')
     *   b) Loads "config.[env].json" to get all env's variables (e.g.: 'config.development.json')
     */
    public load() {
        return new Promise((resolve, reject) => {
            if (AppConfig.config != null || AppConfig.env != null) {
                return resolve(true);
            }

            this.http.get('env.json').map( res => res.json() ).subscribe( (envResponse) => {
                AppConfig.env = envResponse;
                let request:any = null;

                switch (envResponse.env) {
                    case 'production': {
                        request = this.http.get('config.' + envResponse.env + '.json');
                    } break;

                    case 'development': {
                        request = this.http.get('config.' + envResponse.env + '.json');
                    } break;

                    case 'default': {
                        alert('Database adapter not defined');
                    } break;
                }

                request
                    .map( res => res.json() )
                    .catch((error: any) => {
                        console.error(error);
                        reject(error);
                        return Observable.throw(error.json().error || 'Server error');
                    })
                    .subscribe((responseData) => {
                        AppConfig.config = responseData;
                        resolve(true);
                    });
            });

        });
    }
}

In env.json

{
    "env": "development"
}

In config.development.json

{
    "host": "localhost"
}

In config.production.json

{
    "host": "112.164.12.21"
}

In Any Angular2 class

import { AppConfig } from './app.config';

export class AnyClass {
    constructor(private config: AppConfig) {
    
    }
    
    myMethod() {
        let host:string = config.get('host');
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment