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

时间:2016-06-23 13:11:37

标签: typescript configuration angular config preload

我正在帮助使用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];
    }
}

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

//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);
    }
}

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

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

    1. 向angular2应用程序添加可配置性的其他一些方法。

1 个答案:

答案 0 :(得分:0)

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

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