我正在使用gulp
来运行和构建我的应用程序。我在 index.js
文件中使用 $http
服务获取文件内容,然后设置变量的值,例如
window.variablex = "http://localhost:8080/appname"
。
这是我的做法(在 index.js
中)
(function ()
{
'use strict';
angular
.module('main')
.controller('IndexController', IndexController);
function IndexController($http){
$http.get('conf/conf.json').success(function(data){
window.variable = data.urlValue;
}).error(function(error){
console.log(error);
});
}
});
我创建了一个工厂来调用后端应用程序的其余 API,例如
(function(){
'use strict';
angular
.module('main')
.factory('testService',['$resource',testService]);
function agentService($resource){
var agents = $resource('../controller/',{id:'@id'},
{
getList:{
method:'GET',
url:window.variable+"/controller/index/",
isArray:false
}
});
现在,我除了进行休息通话
http://localhost:8080/appname/controller
但它总是发送一个类似 http://undefined/appname/controller
的调用,这是不正确的。
我可以在其他任何地方获取新的设置值,但该值并未以某种方式在资源服务
对象中设置。
我肯定错过了一些东西。
任何帮助将不胜感激
最佳答案
由于您正在使用 Gulp,我建议您使用 gulp-ng-config
例如,您有 config.json:
{
"local": {
"EnvironmentConfig": {
"api": "http://localhost/"
}
},
"production": {
"EnvironmentConfig": {
"api": "https://api.production.com/"
}
}
}
那么gulpfile中的用法是:
gulp.task('config', function () {
gulp.src('config.json')
.pipe(gulpNgConfig('main.config', {
environment: 'production'
}))
.pipe(gulp.dest('.'))
});
您将得到以下输出:
angular.module('myApp.config', [])
.constant('EnvironmentConfig', {"api": "https://api.production.com/"});
然后,您必须在 app.js 中添加该模块
angular.module('main', [ 'main.config' ]);
要使用该变量,您必须在提供程序中注入(inject):
angular
.module('main')
.factory('testService', ['$resource', 'EnvironmentConfig', testService]);
function agentService($resource, EnvironmentConfig) {
var agents = $resource('../controller/', {id: '@id'},
{
getList: {
method: 'GET',
url: EnvironmentConfig + "/controller/index/",
isArray: false
}
});
}
关于javascript - 值未设置为 JS/AngularJs 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46896606/