【问题标题】:Storing environment variables in Angular 2在 Angular 2 中存储环境变量
【发布时间】:2016-06-01 21:24:48
【问题描述】:

我目前正在开发基于angular2-seed 的Angular 2 应用程序。我正在寻找存储环境变量的最佳方法,以便我可以存储不同的值,例如 API url。

默认配置文件 (seed.config.ts) 已经有 2 个用于构建生产或开发的环境:

/**
 * The enumeration of available environments.
 * @type {Environments}
 */
export const ENVIRONMENTS: Environments = {
  DEVELOPMENT: 'dev',
  PRODUCTION: 'prod',
  STAGING: 'staging'
};

在这个配置文件中,定义了一个类 SeedConfig,其中定义了一些常量,我想这也是我应该添加变量的地方。这给了我:

export class SeedConfig {

  PORT = argv['port'] || 8000;
  URL_DEV = 'www.example.com';
  URL_PROD = 'www.example.com';

现在,根据配置的环境,在我的模板中访问这些变量的最佳方法是什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

    1)

    提供课程

    bootstrap(AppComponent, [provide('SeedConfig', {useClass: SeedConfig}]);
    

    @Component({
      selector: 'app-component',
      providers: [provide('SeedConfig', {useClass: SeedConfig}],
      ...
    })
    

    像访问它

    @Component({
      selector: 'some-component',
      template: `<div>{{seedConfig.DEVELOPMENT}}</div>
      ...
    })
    export class SomeComponent {
      constructor(@Inject('SeedConfig') private seedConfig:any) {}
    }
    

    2)

    或者获得正确的自动完成

    提供课程

    bootstrap(AppComponent, [SeedConfig]);
    

    @Component({
      selector: 'app-component',
      providers: [SeedConfig],
      ...
    })
    

    像访问它

    @Component({
      selector: 'some-component',
      template: `<div>{{seedConfig.DEVELOPMENT}}</div>
      ...
    })
    export class SomeComponent {
      constructor(private seedConfig:SeedConfig) {}
    }
    

    第二种方法的优点是自动补全可以列出所有配置的属性,但它也需要在任何使用它的地方导入SeedConfig

    【讨论】:

    • 嗯,有一点我不确定如何继续,我不需要模板中的变量,而是我的组件中的变量。如何访问组件中的这些变量?
    • this.seedConfig.DEVELOPMENT
    • @GünterZöchbauer 将这些变量保存在 environment.ts 中会不会出错?
    • @Sofia 我不明白这个问题。为什么会出错?这通常取决于上下文。
    • 如果您想以不同的值多次部署应用程序,或者如果您想在开发、登台、生产等之间使用不同的值,那么将常量放在那里并没有错。
    猜你喜欢
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多