1.app.module.ts
2.app.config.ts
1.新建app.config.ts文件
2.内容:
import { Inject, Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class AppConfig {
private config: Object = null;
private env: Object = null;
constructor(private http: Http) {
}
/**
* Use to get the data found in the second file (config file)
*/
public getConfig(key: any) {
return this.config[key];
}
/**
* Use to get the data found in the first file (env file)
*/
public getEnv(key: any) {
return this.env[key];
}
/**
* This method:
* a) Loads "env.json" to get the current working environment (e.g.: 'production', 'development')
* b) Loads "config.[env].json" to get all env's variables (e.g.: 'config.development.json')
*/
public load() {
return new Promise((resolve, reject) => {
this.http.get('env.json').map( res => res.json() ).catch((error: any):any => {
console.log('Configuration file "env.json" could not be read');
resolve(true);
return Observable.throw(error.json().error || 'Server error');
}).subscribe( (envResponse) => {
this.env = envResponse;
let request:any = null;
switch (envResponse.env) {
case 'production': {
request = this.http.get('config.' + envResponse.env + '.json');
} break;
case 'development': {
request = this.http.get('config.' + envResponse.env + '.json');
} break;
case 'default': {
console.error('Environment file is not set or invalid');
resolve(true);
} break;
}
if (request) {
request
.map( res => res.json() )
.catch((error: any) => {
console.error('Error reading ' + envResponse.env + ' configuration file');
resolve(error);
return Observable.throw(error.json().error || 'Server error');
})
.subscribe((responseData) => {
this.config = responseData;
resolve(true);
});
} else {
console.error('Env config file "env.json" is not valid');
resolve(true);
}
});
});
}
}
3.env.json
在你将配置当前开发环境的地方。允许的值是“development”和“production”
{ "env": "development" }
4.config.development.json
这是你将编写生产配置变量的地方。您可以在JSON文件中添加您想要的变量。
{ "host": "测试地址" }
5.config.production.json
这是你将编写生产配置变量的地方。您可以在JSON文件中添加您想要的变量。
{ "host": "正式发布地址" }
ps:位置参考
6.根据配置读取相应的地址
***1.***我这里写了公共方法,所以在公共方法里直接调AppConfig的方法,获取地址即可
service-base.ts(公共方法)
结束
***2.***或者将读取配置文件单独写在一个.ts文件,即把***1***拆分
2.1:app.commont.ts
import { Injectable, Inject } from "@angular/core";
import { AppConfig } from '../../app/app.config'
@Injectable()
export class AnyClass {
constructor(private config: AppConfig) {
}
myMethodToGetHost() {
return this.config.getConfig('host');
}
}
2.2service-base.ts(公共方法)
结束
本篇内容参考:https://gist.github.com/fernandohu/122e88c3bcd210bbe41c608c36306db9
感谢