我能够解决同样的问题。我有开发、测试和生产环境,它们都需要连接到不同的 API 端点。我可以使用一个名为 grunt-ng-constant 的 grunt 插件来实现这一点
基本上在安装插件后,修改 Gruntfile 并在 grunt.initConfig 中添加如下内容:
ngconstant: {
// Options for all targets
options: {
space: ' ',
wrap: '"use strict";\n\n {%= __ngModule %}',
name: 'config',
},
// Environment targets
development: {
options: {
dest: '<%= yeoman.app %>/scripts/config.js'
},
constants: {
ENV: {
name: 'development',
apiEndpoint: 'http://your-development.api.endpoint:3000'
}
}
},
production: {
options: {
dest: '<%= yeoman.dist %>/scripts/config.js'
},
constants: {
ENV: {
name: 'production',
apiEndpoint: 'http://api.livesite.com'
}
}
}
},
像这样注册 Grunt 任务:
grunt.registerTask('serve', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'ngconstant:development', // ADD THIS
'bower-install',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
现在每次运行 grunt serve 时,它都会生成一个包含 development 常量的 config.js 文件。您可以配置不同的任务,例如 grunt testing 或 grunt production 来生成测试或生产常量。
最后你像这样将 config.js 添加到你的 index.html 中:
<script src="/scripts/config.js" />
并在您的应用中注册配置模块:
var app = angular.module('myApp', [ 'config' ]);
在您的控制器中,您可以像这样获取“环境”变量:
angular.module('myApp')
.controller('MainCtrl', function ($scope, $http, ENV) { // ENV is injected
$scope.login = function() {
$http.post(
ENV.apiEndPoint, // Our environmental var :)
$scope.yourData
).success(function() {
console.log('Cows');
});
};
});
使用这种方法,您可以轻松地自动化整个部署管道。您可以让 CI 服务器将您的更改推送到适当的服务器并构建您的应用程序的正确版本。
这是一个非常有用的资源供您阅读,我从中提取了代码示例:http://mindthecode.com/how-to-use-environment-variables-in-your-angular-application
希望对您有所帮助!