Skip to content

Angular配置文件之环境配置 #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
deepthan opened this issue Nov 14, 2017 · 0 comments
Open

Angular配置文件之环境配置 #2

deepthan opened this issue Nov 14, 2017 · 0 comments

Comments

@deepthan
Copy link
Owner

假设有三个环境:开发环境(dev)、测试环境(test)、生产环境(prod)。
当我们构建参数时会用到 --environment来指定应用执行环境。脚手架会根据指定的值加载对应的环境配置文件。如:ng build --env=dev 就是build开发环境的包。那么我们就从这里开始看看Angular项目里环境该怎么配置。

  1. 首先要找到.angular-cli.json文件的environments关键词进行如下配置:
  "environmentSource": "environments/environment.ts",  // 基础环境配置
  "environments": { // 子环境配置文件
          "dev": "environments/environment.ts",
          "test": "environments/environment.test.ts",
          "prod": "environments/environment.prod.ts"
  }
       
  1. 再进入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"
  }
}
  1. 在项目的service中相对路径引入环境再请求接口,伪代码如下:
...
@Injectable()
export class LoginService {
  public Login(): Observable<any> {
    return this.http.get("/login").map(
      response => {
        return response.json();
      }
    )
   }
}

(完)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant