Angular 2 - How to use config files

后端 未结 1 1163
隐瞒了意图╮
隐瞒了意图╮ 2021-01-29 03:29

When working in ZF2 we use configuration files that may vary from developer to developer and between production and staging environments. Its pretty convenient and as such I wan

相关标签:
1条回答
  • 2021-01-29 04:06

    I also come from a ZF2 background and wanted this sort of functionality. I can't promise that this is the 'convention' for achieving this however it works perfectly for me and my situation.

    In short I use a combination of JSON config files and grunt-ng-constant (requires Grunt obvs..)

    My ngconstant config in my Gruntfile.js looks like this:

    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')
            }
        }
    }
    

    The location of all your files is up to you.. but the theory of this is that config.global.json is where all your default configs go. Then depending on whether you run ngconstant:live or ngconstant:dev it will merge the corresponding config with global and overwrite any overlaps.

    This saves the config to a new Angular constant, public/js/src/config.js, which I can then inject into any service / controller that I want.

    /**
     * My Controller
     */
    angular
        .module('ctrls')
        .controller('myCtrl', myCtrl);
    
    /**
     * @param $scope
     * @param config
     */
    function myCtrl($scope, config)
    {
        $scope.someConfig = config.someConfigValue;
    }
    
    0 讨论(0)
提交回复
热议问题