如何在angular2中预加载配置文件 [英] How to preload a config file in angular2
问题描述
我正在使用webpack帮助开发一个angular2 web应用程序,我们当前的计划是打开一些文件来配置我们的应用程序的功能(可能的.json)。这主要是给予实施我们的应用程序的人一个容易找到的文件来指定以下内容:他们的API位于哪里,如果他们想要添加自定义样式表等。
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];
}
}
我在另一个服务类中使用它: / p>
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);
}
}
我想知道是否有办法加载config.ts:
I'm wondering if there is a way to load config.ts either:
- 在引导应用程序的根组件之前
- li>
- 在调用ApiService的服务方法之前
或
推荐答案
我建议你对生产应用程序足够的解决方案是加载配置文件在 webpack.config.js
,然后使用从webpack中定义插件。
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.
它只是允许你读取任何文件和环境变量,然后将其作为全局变量传递到bundle。
It simply allows you to read any file and environment variable and then pass it to the bundle as global variable.
这篇关于如何在angular2中预加载配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!