带有angular-cli的angular2中的特定于环境的服务端点 [英] Environment specific service endpoint in angular2 with angular-cli

查看:74
本文介绍了带有angular-cli的angular2中的特定于环境的服务端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的angular2项目设置angular-cli.

I am uning angular-cli for my angular2 project.

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

I am calling backend ajax services through my angular2 service.

对于不同的任务,我有不同的服务端点(URL). 我想使这些服务环境有意义.

I have different services end point (URL) for different task. I want to make those services environment sensetive.

假设我有两次服务

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

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

Since localhost is avaliable in my development environment. It is working

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

Now suppose x.x.x.x is my production web service host ip address.

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

So for production environment the service URL will be https://x.x.x.x:8080/customers

请帮助我实现这一目标.

Please help me how to achive this.

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

I found there is a block in angular-cli.json file as

"environments": {
    "source": "environments/environment.ts",
    "dev": "environments/environment.ts",
    "prod": "environments/environment.prod.ts"
}

但是我现在确实找到了环境目录.

But I did now found that environments directory.

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

How to create that and manage environment specific end points?

推荐答案

该命令 ng new PROJECT_NAME 可以创建两个文件:

The command ng new PROJECT_NAME was supposed to create both files:

  • src/environments/environment.prod.ts
  • src/environments/environment.ts

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

I believe you can create it manually. Here is the generated code:

// 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
};

您可以在两个文件中为相应的环境添加所需的配置:

You can add the configuration you need in both files for the respectful environment:

// src/environments/environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:8080'
};

...

// src/environments/environment.prod.ts
export const environment = {
  production: true,
  apiUrl: 'https://x.x.x.x'
};

仅使用配置:

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

//...

let url = `${environment.apiUrl}/customers`;

只需确保您导入的是'../environments/environment',而不是"../environments/environment.prod".

Just make sure you are importing '../environments/environment' and NOT '../environments/environment.prod'.

这篇关于带有angular-cli的angular2中的特定于环境的服务端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆