访问当前应用程序配置的正确方法

Correct way to access current application configuration

我在 myapp/config/environment 中添加了一些配置:

if (environment === 'development') {
  ENV.APP.AuthURL = 'http://localhost:5000/';
}

现在,要访问此配置,我应该使用某种方法还是直接访问 window.Myapp

您可以使用以下行导入 environment.js 来访问它:

import config from '../config/environment';

例如,假设您想访问控制器中的配置。这就是它的样子:

import Ember from 'ember';
import config from '../config/environment';

export default Ember.Controller.extend({
  foo: config.APP.AuthURL
});

如果需要,您现在可以使用以下方法在控制器模板中访问它:

{{foo}}

虽然@rog 的回答是正确的,并且适用于您尝试从 应用程序 访问配置的所有情况,但有一些边缘情况(例如从插件)它不会工作。

我建议查看 ember-get-config 插件:https://www.emberobserver.com/addons/ember-get-config

安装 ember-get-config 后,您可以使用以下代码导入配置:

import config from 'ember-get-config';
const { AuthURL } = config;
// now you have access to AuthURL 

这将在您的应用程序中工作,如果您构建一个将由您的应用程序使用的插件,它也将工作

在撰写本文时,尝试从您的应用程序访问它时,有几种现代方法:

  1. import ENV from 'your-application-name/config/environment';
    • your-application-name 应该是 config/environment.jsmodulePrefix 键和 package.json
    • name 键中的内容
  2. 通过Ember.getOwner(this).resolveRegistration('config:environment');

第一个假定您正在使用 Ember CLI,并且在 Configuring Your App 下的 ember 文档中有详细说明:

Ember CLI ships with support for managing your application's environment. Ember CLI will setup a default environment config file at config/environment. Here, you can define an ENV object for each environment, which are currently limited to three: development, test, and production.

The ENV object contains three important keys:

  • EmberENV can be used to define Ember feature flags (see the Feature Flags guide).
  • APP can be used to pass flags/options to your application instance.
  • environment contains the name of the current environment (development,production or test).

You can access these environment variables in your application code by importing from your-application-name/config/environment.