在Angular项目的设计中,我们往往需要定义一些全局的数据,如:应用名称,版本,当前环境,后端服务器地址,当前用户信息等,并希望能一次定义,多处共享,这里我们介绍如何用service来为整个应用提供全局配置服务。
(1) 应用环境
1. 定义名为App_Configuration的interface,该配置中,我们定义了应用的基本信息字段,开发环境和生产环境的参数类型
//App_Configuration..config.ts
export interface App_Configuration{
app:{
base:{
name:string,
version:string
},
environments:{
dev:{
API:{
service:{
report:string
},
backend:{
schema:string,
core:string
}
}
},
prod:{
API:{
service:{
report:string
},
backend:{
schema:string,
core:string
}
}
}
}
}
}
2. 配置一个 App_Config 常量
import { App_Configuration } from './app.config.interface';
console.log('import App_Configuration..');
export const App_Config: App_Configuration = {
app:{
base:{
name:'Ng_App_Demo',
version:'0.1'
},
environments:{
dev:{
API:{
service:{
report:'http://xx.xx.xx.xx:yyyy'
},
backend:{
schema:'http://xx.xx.xx.xx:yyyy',
core:'http://zz.zz.zz.zz:yyyy'
}
}
},
prod:{
API:{
service:{
report:'http://aa.aa.aa.aa:yyyy'
},
backend:{
schema:'http://bb.bb.bb.bb:yyyy',
core:'http://cc.cc.cc.cc:yyyy'
}
}
}
}
}
};
3. 定义一个 environment.helper.ts
import { App_Config } from '../configurations/app.config'
export const EnvHelper = {
getEnvConfig:function(siteUrl){
let envType = EnvHelper.getEnvType(siteUrl);
let config;
//根据当前用户访问地址,匹配到对应环境的配置信息
switch(envType){
case 'dev':
config = App_Config.app.environments.dev;
break;
case 'prod':
config = App_Config.app.environments.prod;
break;
default:
config = App_Config.app.environments.dev;
break;
}
return config;
},
getHostName:function(url){
let parser = document.createElement('a');
parser.href = url;
return parser.host;
},
getEnvType:function(url){
if(EnvHelper.isDevelopment(url)){
return 'dev';
}
if(EnvHelper.isProduction(url)){
return 'prod';
}
},
//当前是否为测试环境
isDevelopment:function(siteUrl){
let devHosts = App_Config.app.environments.dev.others.ENV.hosts;
if(devHosts.indexOf(EnvHelper.getHostName(siteUrl)) !== -1){
return true;
}
return false;
},
//当前是否为生产环境
isProduction:function(siteUrl){
let prodHosts = App_Config.app.environments.prod.others.ENV.hosts;
if(prodHosts.indexOf(EnvHelper.getHostName(siteUrl)) !== -1){
return true;
}
return false;
}
};
4. 提供一个 environment service
import { Injectable } from '@angular/core';
import { EnvHelper } from '../helpers/environment.helper';
export type SiteStateType = {
[key: string]: any
};
@Injectable()
export class EnvSvc{
_envState:SiteStateType = {
url:window.location.href,
//调用EnvHelper得到当前应用环境配置
config:EnvHelper.getEnvConfig(window.location.href)
};
constructor() {
}
get envState(){
//在开放的获取应用环境状态时,克隆一份_envState,避免外部程序修改配置
return this._envState = this._clone(this._envState);
}
set envState(value) {
throw new Error('do not mutate the `.envState` directly');
}
get(prop?: any){
const state = this.envState;
return state.hasOwnProperty(prop) ? state[prop] : state;
}
private _clone(object: SiteStateType){
return JSON.parse(JSON.stringify(object));
}
}
5. 在app.module.ts 中providers 添加EnvSvc并在相应component中注入即可。