具有angular-cli的angular2中的环境特定服务端点

Par*_*osh 3 angular-cli angular

我正在为angular2项目取得angular-cli.

我通过我的angular2服务调用后端ajax服务.

我为不同的任务提供不同的服务端点(URL).我想让这些服务环境有意义.

假设我有两个服务

  1. 客户服务 : https://localhost:8080/customers
  2. 产品服务: https://localhost:8080/products

因为localhost在我的开发环境中是可用的.这是工作

现在假设x.x.x.x是我的生产Web服务主机IP地址.

因此,对于生产环境,服务URL将为https:// xxxx:8080/customers

请帮我解决这个问题.

我发现angular-cli.json文件中有一个块

"environments": {
    "source": "environments/environment.ts",
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
}
Run Code Online (Sandbox Code Playgroud)

但我现在发现了环境目录.

如何创建和管理特定于环境的端点?

fel*_*ima 6

命令新的PROJECT_NAME应该创建两个文件:

  • SRC /环境/ environment.prod.ts
  • SRC /环境/ environment.ts

我相信你可以手动创建它.这是生成的代码:

// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `angular-cli.json`.

export const environment = {
  production: false
};
Run Code Online (Sandbox Code Playgroud)

您可以在两个文件中添加所需的配置以满足尊重的环境:

// src/environments/environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:8080'
};
Run Code Online (Sandbox Code Playgroud)

...

// src/environments/environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'https://x.x.x.x'
};
Run Code Online (Sandbox Code Playgroud)

要使用配置:

import { environment } from '../environments/environment';

//...

let url = `${environment.apiUrl}/customers`;
Run Code Online (Sandbox Code Playgroud)

只需确保输入'../environments/environment'而不是'../environments/environment.prod'.