我正在帮助使用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:
OR
答案 0 :(得分:0)
我建议你对生产应用程序做得足够好的解决方案是在webpack.config.js
中加载配置文件,然后在webpack中使用Define Plugin。
它只是允许您读取任何文件和环境变量,然后将其作为全局变量传递给bundle。