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

6

我正在使用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的服务方法之前

或者

  1. 其他完全不同的为Angular2应用程序添加可配置性的方式。

你可以使用简单的“config”服务来引导所有配置,然后从任何可配置的地方访问它。 - Ankit Singh
如果我理解正确的话,我已经尝试将Config添加到引导提供程序中。问题在于,在Config完成加载之前就会进行ApiService调用,这些调用依赖于Config完全加载。 - JonJonH
1个回答

0
我建议你使用的解决方案,适用于生产应用程序,是在webpack.config.js中加载配置文件,然后使用webpack的Define Plugin
它简单地允许你读取任何文件和环境变量,然后将其作为全局变量传递给bundle。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接