Angular 2 - 如何使用配置文件

时间:2016-04-21 10:07:49

标签: angular

在ZF2中工作时,我们使用的配置文件可能因开发人员和开发人员之间以及生产环境和登台环境而异。它非常方便,因此我想为Angular 2复制它。

它在ZF2中是如何工作的:我们有一个配置文件夹,配置名为:settings.local.php和settings.global.php。然后我们使用gitignore文件来忽略其中包含local的任何内容。

我想和Angular 2做类似的事情,并不是100%肯定最好的方法。

对于Angular 2,我考虑使用配置文件夹,然后使用服务来获取配置文件......

在Angular 2中是否存在类似这样的约定?

1 个答案:

答案 0 :(得分:0)

我也来自ZF2背景,想要这种功能。我不能保证这是实现这一目标的“惯例”,但它对我和我的情况都很有效。

简而言之,我使用了JSON配置文件和grunt-ng-constant的组合(需要Grunt obvs。)

我的ngconstant中的Gruntfile.js个配置如下所示:

ngconstant: {
    options: {
        constants: {
            config: grunt.file.readJSON('config/config.global.json')
        },
        name: 'constants',
        dest: 'public/js/src/config.js',
        wrap: '/* global angular */\n\n(function ()\n{\n\t\'use strict\';\n\t\n\t{%= __ngModule %}\n\t\n})();\n'
    },
    dev: {
        constants: {
            config: grunt.file.readJSON('config/config.dev.json')
        }
    },
    live: {
        constants: {
            config: grunt.file.readJSON('config/config.live.json')
        }
    }
}

您所有文件的位置取决于您..但理论是config.global.json是您所有默认配置的所在。然后,根据您是运行ngconstant:live还是ngconstant:dev,它会将相应的配置与全局合并,并覆盖任何重叠。

这会将配置保存到新的Angular constantpublic/js/src/config.js,然后我可以将其注入到我想要的任何服务/控制器中。

/**
 * My Controller
 */
angular
    .module('ctrls')
    .controller('myCtrl', myCtrl);

/**
 * @param $scope
 * @param config
 */
function myCtrl($scope, config)
{
    $scope.someConfig = config.someConfigValue;
}