假设有三个环境:开发环境(dev)、测试环境(test)、生产环境(prod)。
当我们构建参数时会用到 --environment来指定应用执行环境。脚手架会根据指定的值加载对应的环境配置文件。如:ng build --env=dev 就是build开发环境的包。那么我们就从这里开始看看Angular项目里环境该怎么配置。
- 首先要找到.angular-cli.json文件的environments关键词进行如下配置:
"environmentSource": "environments/environment.ts", // 基础环境配置
"environments": { // 子环境配置文件
"dev": "environments/environment.ts",
"test": "environments/environment.test.ts",
"prod": "environments/environment.prod.ts"
}
- 再进入environments文件夹
文件目录:
├─ environments
│ ├─ common.json
│ ├─ environment.ts
│ ├─ development.json
│ ├─ environment.test.ts
│ ├─ test.json
│ ├─ environment.prod.ts
│ └─ production.json
│
- 这里可以创建一个 common.json文件以存储三套环境公共的配置:
{
"title": "",
"question": {
"url": ""
},
"list": {
"pageSize": 10
}
}
开发环境 :
- environment.ts
export const environment = Object.assign({}, require('./common.json'), require('./development.json'), {
production: false,
envName: 'dev'
});
- development.json
{
"baseUrl": "/",
"env": "dev",
"api": {
"host": "http://localhost:4200"
}
}
测试环境:
- environment.test.ts
export const environment = Object.assign({}, require('./common.json'), require('./test.json'), {
production: false,
envName: 'test'
});
- test.json
{
"baseUrl": "/",
"env": "test",
"api": {
"host": "testurl"
}
}
生产环境:
- environment.prod.ts
export const environment = Object.assign({}, require('./common.json'), require('./production.json'), {
production: true,
envName: 'prod'
});
- production.json
{
"baseUrl": "/",
"env": "prod",
"api": {
"host": "produrl"
}
}
- 在项目的service中相对路径引入环境再请求接口,伪代码如下:
...
@Injectable()
export class LoginService {
public Login(): Observable<any> {
return this.http.get("/login").map(
response => {
return response.json();
}
)
}
}