如何在Angular.js中配置不同的环境?

rba*_*ani 218 javascript angularjs angularjs-service

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

这可能是一个例子:

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

假设我们有这样的事情:

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

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

    .factory('User', function($resource, API_END_POINT) {
        return $resource(API_END_POINT + 'user');
    });
Run Code Online (Sandbox Code Playgroud)

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

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

And*_*ion 209

我有点迟到了,但是如果你使用Grunt我已经取得了很大的成功grunt-ng-constant.

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

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'
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用的任务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'
]);
Run Code Online (Sandbox Code Playgroud)

所以运行grunt server会生成一个看起来像的config.js文件app/scripts/

"use strict";
angular.module("config", []).constant("ENV", "development");
Run Code Online (Sandbox Code Playgroud)

最后,我声明了对任何模块的依赖:

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

现在,我的常量可以在需要时进行依赖注入.例如,

app.controller('MyController', ['ENV', function( ENV ) {
  if( ENV === 'production' ) {
    ...
  }
}]);
Run Code Online (Sandbox Code Playgroud)

  • 而不是在''serve'中加入''ngconstant:development' - 如果你把它放在''gruntfile'下的watch命令中作为`tasks:['ngconstant:development']` - 你就不需要重新启动了当你更新gruntfile中的开发变量时,`grunt serve`. (10认同)
  • 你可以放入单独的文件,而不是在gruntfile.js中添加常量:`package:grunt.file.readJSON('development.json')` (10认同)
  • 对于那些使用gulp的人来说,有[gulp-ng-constant](https://www.npmjs.org/package/gulp-ng-constant). (10认同)
  • 我发现还需要将scripts/config.js文件包含到angular来查找模块,如下所示:<script src ="scripts/config.js"> </ script> (4认同)
  • 在grunt-ng-constant的0.5版本中有Gruntfile.js的更新语法:https://github.com/werk85/grunt-ng-constant/issues/31.很好的回答,谢谢! (3认同)

kfi*_*fis 75

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

angular.module('configuration', [])
       .constant('API_END_POINT','123456')
       .constant('HOST','localhost');
Run Code Online (Sandbox Code Playgroud)

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

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

现在你可以考虑进一步的酷事:

包含配置的模块可以分为configuration.js,它将包含在您的页面中.

只要您不将此单独的文件检入git,您就可以轻松地编辑此脚本.但是,如果配置位于单独的文件中,则更容易检查配置.此外,您可以在本地分支.

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

或者你有你的configuration_a.js并且configuration_b.js在后端决定要包含哪些内容.


Rim*_*ian 30

对于Gulp用户,gulp-ng-constantgulp -concat,event-streamyargs结合使用也很有用.

var concat = require('gulp-concat'),
    es = require('event-stream'),
    gulp = require('gulp'),
    ngConstant = require('gulp-ng-constant'),
    argv = require('yargs').argv;

var enviroment = argv.env || 'development';

gulp.task('config', function () {
  var config = gulp.src('config/' + enviroment + '.json')
    .pipe(ngConstant({name: 'app.config'}));
  var scripts = gulp.src('js/*');
  return es.merge(config, scripts)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('app/dist'))
    .on('error', function() { });
});
Run Code Online (Sandbox Code Playgroud)

在我的配置文件夹中,我有以下文件:

ls -l config
total 8
-rw-r--r--+ 1 .. ci.json
-rw-r--r--+ 1 .. development.json
-rw-r--r--+ 1 .. production.json
Run Code Online (Sandbox Code Playgroud)

然后你可以运行gulp config --env development,这将创建这样的东西:

angular.module("app.config", [])
.constant("foo", "bar")
.constant("ngConstant", true);
Run Code Online (Sandbox Code Playgroud)

我也有这个规格:

beforeEach(module('app'));

it('loads the config', inject(function(config) {
  expect(config).toBeTruthy();
}));
Run Code Online (Sandbox Code Playgroud)


Jua*_*gos 17

为此,我建议您使用AngularJS Environment Plugin:https://www.npmjs.com/package/angular-environment

这是一个例子:

angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
    // set the domains and variables for each environment 
    envServiceProvider.config({
        domains: {
            development: ['localhost', 'dev.local'],
            production: ['acme.com', 'acme.net', 'acme.org']
            // anotherStage: ['domain1', 'domain2'], 
            // anotherStage: ['domain1', 'domain2'] 
        },
        vars: {
            development: {
                apiUrl: '//localhost/api',
                staticUrl: '//localhost/static'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            },
            production: {
                apiUrl: '//api.acme.com/v2',
                staticUrl: '//static.acme.com'
                // antoherCustomVar: 'lorem', 
                // antoherCustomVar: 'ipsum' 
            }
            // anotherStage: { 
            //  customVar: 'lorem', 
            //  customVar: 'ipsum' 
            // } 
        }
    });

    // run the environment check, so the comprobation is made 
    // before controllers and services are built 
    envServiceProvider.check();
});
Run Code Online (Sandbox Code Playgroud)

然后,您可以从控制器调用变量,例如:

envService.read('apiUrl');
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Jur*_*lav 13

您可以使用lvh.me:9000访问AngularJS应用程序(lvh.me仅指向127.0.0.1),然后指定不同的端点(如果lvh.me是主机):

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/';
  }
});
Run Code Online (Sandbox Code Playgroud)

然后注入Configuration服务并Configuration.API在需要访问API的任何地方使用:

$resource(Configuration.API + '/endpoint/:id', {
  id: '@id'
});
Run Code Online (Sandbox Code Playgroud)

有点笨重,但对我来说很好,虽然情况略有不同(API端点在生产和开发方面有所不同).


Tha*_*var 6

我们也可以这样做.

(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];
            }
        }

    });

})();
Run Code Online (Sandbox Code Playgroud)

在您的中controller/service,我们可以注入依赖项并使用要访问的属性调用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;
    }

})();
Run Code Online (Sandbox Code Playgroud)

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


joa*_*eng 5

好问题!

一种解决方案可能是继续使用您的config.xml文件,并从后端向您生成的html提供api端点信息,如下所示(例如在php中):

<script type="text/javascript">
angular.module('YourApp').constant('API_END_POINT', '<?php echo $apiEndPointFromBackend; ?>');
</script>
Run Code Online (Sandbox Code Playgroud)

也许不是一个漂亮的解决方案,但它会起作用.

另一种解决方案可能是保持生产中的API_END_POINT常量值,并且只修改hosts-file以将该url指向本地api.

或者也许是localStorage用于覆盖的解决方案,如下所示:

.factory('User',['$resource','API_END_POINT'],function($resource,API_END_POINT){
   var myApi = localStorage.get('myLocalApiOverride');
   return $resource((myApi || API_END_POINT) + 'user');
});
Run Code Online (Sandbox Code Playgroud)