【问题标题】:Setup the environment variables of angular 2 project设置 Angular 2 项目的环境变量
【发布时间】:2017-06-01 08:01:18
【问题描述】:

我正在处理一个带有 typescript 和 webpack 的 angular 2 项目。 在开发时我应该使用本地 API 或测试 API。 但是在生产中我应该使用真正的 API。所以 API URL 会改变。

API 用于产品服务等许多服务文件中。

我想将我所有的 API URL 写在一个文件中,以便在环境发生变化时可以轻松更改 URL。

我该怎么做?

【问题讨论】:

标签: angular typescript webpack


【解决方案1】:

您可以创建一个配置文件并将您的配置值存储为 object 键值。

config.ts:

export var config = {
  title: "Hello World",
  "SecurityService":"http://localhost/SecurityAPI",
  "CacheService":"http://localhost/CacheServiceAPI"
}

yourComponent.ts:

import { config } from './config';

myTitle = config.title;

完整示例:http://plnkr.co/edit/CGtxYJkcjYt2cEzrbL00?p=info

您还可以对外部配置文件 (json) 发出 http 请求;

Plunker:http://plnkr.co/edit/60E2qb9gOjvkEAeR5CtE?p=info

【讨论】:

    【解决方案2】:

    您可以创建具有静态属性的 TS 类:

    export class Environment {
       public static API_ENDPOINT = 'http://127.0.0.1:6666/api/';
    }
    

    如下使用:

    import { Environment } from './environment';
    
    export class MyClass {
        apiEndpoint: string = Environment.API_ENDPOINT;
        ...
    }
    

    您还可以创建const 对象:

    export const environment = {
         API_ENDPOINT: 'http://127.0.0.1:6666/api/'
    }
    

    并像这样使用它:

    import { environment } from './environment';
    
    export class MyClass {
        apiEndpoint: string = environment.API_ENDPOINT;
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      • 2018-01-29
      • 2019-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2019-12-14
      相关资源
      最近更新 更多