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

查看:31
本文介绍了带有 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

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

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

现在假设 x.x.x.x 是我的生产网络服务主机 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天全站免登陆