6

I am helping to develop an angular2 web app using webpack, and our current plan is to open up some sort of file for configuring the functionality of our application (.json probably). This would mostly be to give the people implementing our app an easy-to-locate file to specify things like: where their API is located, if they want to add custom stylesheets, etc.

The service I'm using to load my config file looks like this:

//config.ts
@Injectable()
export class Config {
    private static _config: Object;
    private static _promise: Promise<any>;

    constructor(private http: Http) {
        Config._promise = this.load();
    }

    load() {
        return new Promise((resolve, reject) => {
            this.http.get(`./config/development.json`)
                .map((response: Response) => response.json())
                .catch((error: any) => {
                    console.error(error);
                    return Observable.throw(error.json().error || 'Server error');
                })
                .subscribe((data) => {
                    Config._config = data;
                    resolve(true);
                });
        });
    }

    get(key: any) {
        return  Config._config[key];
    }
}

And I am using it in another service class:

//api.service.ts
@Injectable()
export class ApiService {
    private URI: string;

    constructor(private http: Http, private _config: Config) {
        this.URI = this._config.get('apiUrl');
    }

    getCustomQueries(): Observable<any> {
        return this.http
            .get(`${this.URI}/CustomQuery`)
            .map((response: Response) => {
                let data = response.json();
                return { QueryID: data.id, QueryName: data.name };
            })
            .catch(this.handleError);
    }
}

I'm wondering if there is a way to load config.ts either:

  1. Before bootstrapping the application's root component
  2. Before ApiService gets instantiated
  3. Before a service method from ApiService gets called

OR

  1. Some entirely other way of adding configurability to an angular2 application.
JonJonH
  • 61
  • 2
  • you can bootstrap a simple `config` service with all the configuration, and then access it from anything that is configurable. – Ankit Singh Jun 23 '16 at 13:21
  • If I'm understanding you correctly, I've tried simply adding Config to the bootstrapped providers. The problem is that ApiService calls are being made before Config has finished loading, which depend on Config being completely loaded. – JonJonH Jun 23 '16 at 13:31

1 Answers1

0

The solution I'd advice you which is good enough for production apps is to load config file in webpack.config.js and then use Define Plugin from webpack.

It simply allows you to read any file and environment variable and then pass it to the bundle as global variable.

Wojciech Kwiatek
  • 6,634
  • 2
  • 16
  • 26