在Angular 2中存储环境变量

时间:2016-06-01 13:12:41

标签: angular

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

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

/**
 * 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';

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

1 个答案:

答案 0 :(得分: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

相关问题