0

I’d like to create a configuration something that comes from the server side, depends on the current environment (development, staging, qa, production, etc.) and can be queried by my components.

Based on other answers here on SO I came up with a Config object that loads an environment.json file from the server, reads the environment key from that JSON data, and then loads the appropriate config-<env>.json file from the server into its private _config member.

All is good, except that Config.load() (the one that loads the before mentioned files) does asynchronous requests, thus, when I try to use my config.get('myConfigValue') method, it throws an exception, as Config._config is not initialized yet.

What is the correct way to do this?

I’m using Angular 2.0.0 RC6. Below is my config.ts file.

import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Http } from "@angular/http";

@Injectable()
export class Config {
    private _config: Object = null;
    private _env: Object = null;

    constructor(private http: Http) {}

    load() {
        return new Promise((resolve, reject) => {
            this.http.get("app/config/env.json")
                .map(res => res.json())
                .subscribe((env_data) => {
                    this._env = env_data;

                    this.http.get("app/config/" + env_data.env + ".json")
                        .map(res => res.json())
                        .catch((error: any) => {
                            console.error(error);

                            return Observable.throw(error.json().error || `Server error`);
                        })
                        .subscribe((data) => {
                            this._config = data;
                            resolve(true);
                        });
                });
        });
    }

    getEnv(key: any) {
        return this._env[key];
    }

    get(key: any) {
        return this._config[key];
    }
}
GergelyPolonkai
  • 6,230
  • 6
  • 35
  • 69
  • 1
    Sounds like http://stackoverflow.com/questions/37611549/how-to-pass-parameters-rendered-from-backend-to-angular2-bootstrap-method/37611614#37611614 and http://stackoverflow.com/questions/39033835/angularjs2-preload-server-configuration-before-the-application-starts/39033958#39033958 – Günter Zöchbauer Sep 02 '16 at 12:18
  • 1
    I wonder why my search-fu didn’t bring up these… I ran through them and they seem to be good for me. If so, I’ll close this question. – GergelyPolonkai Sep 02 '16 at 12:21

0 Answers0