如何管理不同环境的配置变量/常数?

这可以是一个例子:

我的其余API可以在localhost:7080/myapi/上访问,但是我的朋友在Git版本控制下使用相同的代码,他在localhost:8099/hisapi/上的Tomcat上部署了API。

假设我们有这样的东西:

angular
    .module('app', ['ngResource'])

    .constant('API_END_POINT','<local_end_point>')

    .factory('User', function($resource, API_END_POINT) {
        return $resource(API_END_POINT + 'user');
    });

我如何动态地注入API端点的正确值,取决于环境?

在PHP中,我通常使用config.username.xml文件来完成这类工作,将基本配置文件(config.xml)与由用户名识别的本地环境配置文件合并。但我不知道如何在JavaScript中管理这种事情?


当前回答

你可以用lvh。me:9000来访问你的AngularJS应用程序,(lvh。Me只是指向127.0.0.1),然后指定一个不同的端点如果lvh。我是主持人:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

然后注入Configuration服务并使用Configuration。当你需要访问API时:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

有点笨拙,但对我来说很好,尽管在稍微不同的情况下(API端点在生产和开发中不同)。

其他回答

你可以用lvh。me:9000来访问你的AngularJS应用程序,(lvh。Me只是指向127.0.0.1),然后指定一个不同的端点如果lvh。我是主持人:

app.service("Configuration", function() {
  if (window.location.host.match(/lvh\.me/)) {
    return this.API = 'http://localhost\\:7080/myapi/';
  } else {
    return this.API = 'http://localhost\\:8099/hisapi/';
  }
});

然后注入Configuration服务并使用Configuration。当你需要访问API时:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});

有点笨拙,但对我来说很好,尽管在稍微不同的情况下(API端点在生产和开发中不同)。

你看过这个问题和答案吗?

你可以像这样为你的应用程序设置一个全局有效值:

app.value('key', 'value');

然后用在你的服务上。您可以将这段代码移动到config.js文件中,并在页面加载或其他方便的时候执行。

我们也可以这样做。

(function(){
    'use strict';

    angular.module('app').service('env', function env() {

        var _environments = {
            local: {
                host: 'localhost:3000',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            dev: {
                host: 'dev.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            test: {
                host: 'test.com',
                config: {
                    apiroot: 'http://localhost:3000'
                }
            },
            stage: {
                host: 'stage.com',
                config: {
                apiroot: 'staging'
                }
            },
            prod: {
                host: 'production.com',
                config: {
                    apiroot: 'production'
                }
            }
        },
        _environment;

        return {
            getEnvironment: function(){
                var host = window.location.host;
                if(_environment){
                    return _environment;
                }

                for(var environment in _environments){
                    if(typeof _environments[environment].host && _environments[environment].host == host){
                        _environment = environment;
                        return _environment;
                    }
                }

                return null;
            },
            get: function(property){
                return _environments[this.getEnvironment()].config[property];
            }
        }

    });

})();

在你的控制器/服务中,我们可以注入依赖项并调用get方法来访问属性。

(function() {
    'use strict';

    angular.module('app').service('apiService', apiService);

    apiService.$inject = ['configurations', '$q', '$http', 'env'];

    function apiService(config, $q, $http, env) {

        var service = {};
        /* **********APIs **************** */
        service.get = function() {
            return $http.get(env.get('apiroot') + '/api/yourservice');
        };

        return service;
    }

})();

$http.get(env.get('apiroot')将根据主机环境返回url。

一个很酷的解决方案可能是将所有特定于环境的值分离到某个单独的角模块中,所有其他模块都依赖于它:

angular.module('configuration', [])
       .constant('API_END_POINT','123456')
       .constant('HOST','localhost');

然后需要这些条目的模块可以声明对它的依赖:

angular.module('services',['configuration'])
       .factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
           return $resource(API_END_POINT + 'user');
       });

现在你可以想想更酷的东西:

包含配置的模块可以被分离到configuration.js中,它将包含在你的页面中。

只要不将这个单独的文件签入git,每个人都可以轻松地编辑这个脚本。但是,如果配置在一个单独的文件中,则更容易不签入配置。此外,您还可以在本地对其进行分支。

现在,如果您有一个构建系统,如ANT或Maven,您的进一步步骤可能是为API_END_POINT值实现一些占位符,这些占位符将在构建时用您的特定值替换。

或者你有你的configuration_a.js和configuration_b.js,并在后端决定包含哪个。

我有点晚了,但如果你正在使用Grunt,我已经成功地使用了Grunt -ng-constant。

在我的Gruntfile.js中ngconstant的配置部分看起来像这样

ngconstant: {
  options: {
    name: 'config',
    wrap: '"use strict";\n\n{%= __ngModule %}',
    space: '  '
  },
  development: {
    options: {
      dest: '<%= yeoman.app %>/scripts/config.js'
    },
    constants: {
      ENV: 'development'
    }
  },
  production: {
    options: {
      dest: '<%= yeoman.dist %>/scripts/config.js'
    },
    constants: {
      ENV: 'production'
    }
  }
}

使用ngconstant的任务如下所示

grunt.registerTask('server', function (target) {
  if (target === 'dist') {
    return grunt.task.run([
      'build',
      'open',
      'connect:dist:keepalive'
    ]);
  }

  grunt.task.run([
    'clean:server',
    'ngconstant:development',
    'concurrent:server',
    'connect:livereload',
    'open',
    'watch'
  ]);
});

grunt.registerTask('build', [
  'clean:dist',
  'ngconstant:production',
  'useminPrepare',
  'concurrent:dist',
  'concat',
  'copy',
  'cdnify',
  'ngmin',
  'cssmin',
  'uglify',
  'rev',
  'usemin'
]);

因此,运行grunt服务器将在app/scripts/中生成一个config.js文件,看起来像

"use strict";
angular.module("config", []).constant("ENV", "development");

最后,我声明依赖于任何需要它的模块:

// the 'config' dependency is generated via grunt
var app = angular.module('myApp', [ 'config' ]);

现在我的常量可以在需要的地方被注入依赖项。例如,

app.controller('MyController', ['ENV', function( ENV ) {
  if( ENV === 'production' ) {
    ...
  }
}]);