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:
要么
我建议您对于生产应用程序来说足够好的解决方案是加载配置文件webpack.config.js,然后使用webpack 中的Define Plugin。
它只是允许您读取任何文件和环境变量,然后将其作为全局变量传递给包。
| 归档时间: |
|
| 查看次数: |
2347 次 |
| 最近记录: |