加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 09:31:28 所属栏目:安全 来源:网络整理
导读:如何管理不同环境的配置变量/常量? 这可能是一个例子: 我的rest API是可以在localhost:7080 / myapi /,但我的朋友工作相同的代码在Git版本控制下的API部署在他的Tomcat在localhost:8099 / hisapi /。 假设我们有这样的: angular .module('app',['ngRes
如何管理不同环境的配置变量/常量?

这可能是一个例子:

我的rest API是可以在localhost:7080 / myapi /,但我的朋友工作相同的代码在Git版本控制下的API部署在他的Tomcat在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');
    });

如何根据环境动态注入API端点的正确值?

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

我有点迟到的线程,但如果你使用 Grunt我在 grunt-ng-constant取得了巨大的成功。

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

ngconstant: {
  options: {
    name: 'config',wrap: '"use strict";nn{%= __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','watch'
  ]);
});

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

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

"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' ) {
    ...
  }
}]);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读