How to preload a config file in angular2

别来无恙 提交于 2020-01-14 08:46:06

问题


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.

回答1:


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.



来源:https://stackoverflow.com/questions/37992671/how-to-preload-a-config-file-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!