如何在angular2中预加载配置文件

Jon*_*onH 6 configuration config preload typescript angular

我正在帮助使用webpack开发angular2 web应用程序,我们当前的计划是打开某种文件来配置我们的应用程序的功能(可能是.json).这主要是为了让人们实现我们的应用程序一个易于定位的文件,以指定以下内容:他们的API位于何处,是否要添加自定义样式表等.

我用来加载配置文件的服务如下所示:

//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];
    }
}
Run Code Online (Sandbox Code Playgroud)

我在另一个服务类中使用它:

//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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法加载config.ts:

  1. 在引导应用程序的根组件之前
  2. 在ApiService实例化之前
  3. 在调用ApiService的服务方法之前

要么

  1. 一些完全以其他方式向angular2应用程序添加可配置性.

Woj*_*tek 0

我建议您对于生产应用程序来说足够好的解决方案是加载配置文件webpack.config.js,然后使用webpack 中的Define Plugin

它只是允许您读取任何文件和环境变量,然后将其作为全局变量传递给包。