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];
}
}