Javascript 以角度读取属性文件值
我已经阅读了一些关于使用Javascript 以角度读取属性文件值,javascript,angularjs,angularjs-service,Javascript,Angularjs,Angularjs Service,我已经阅读了一些关于使用$http服务访问属性文件的回复,但现在确定它如何适合这种情况 我已经创建了一个从poperties文件返回主机名的服务,该服务的调用客户端应该对该服务进行阻塞调用,并且只有在读取属性文件时才能继续 var serviceMod = angular.module('serviceModule',[]) .factory('configService', function($http){ return { getValue: function(key
$http
服务访问属性文件的回复,但现在确定它如何适合这种情况
我已经创建了一个从poperties文件返回主机名的服务,该服务的调用客户端应该对该服务进行阻塞调用,并且只有在读取属性文件时才能继续
var serviceMod = angular.module('serviceModule',[])
.factory('configService', function($http){
return {
getValue: function(key){
$http.get("js/resources/urls.properties").success(function(response){
console.log('how to send this response to clients sync??? ' + response)
})
return ????
}
}
})
someothercontroller.js
var urlValue = configService.getValue('url')
我面临的问题与
$http
服务的aync性质有关。当回调收到响应时,主线程已经完成了执行someOtherController.js的过程。您需要解析服务返回的承诺。我们只需返回$http
调用并在控制器中解决它(因为返回$http.get
本身就是一个承诺)。查看AngularJS和文档,以更好地了解正在进行的基本力学,并观察以下变化
.factory('configService', function($http) {
return {
getValue: function(key) {
return $http.get('js/resources/urls.properties');
}
}
});
简单方法-使用回调(它仍然是异步的。事实上,您无法使其同步):
所以每次我们需要访问调用userController.js中的url时,我必须在响应块中编写客户端代码?嗯,这只是静态数据吗?为什么不将
设置为常量
或将其置于应用程序中的$rootScope
上。运行块?你能再解释一下你需要它做什么,多久一次,以及它是否会改变吗?还有,你是偶然使用ui路由器吗?它不能是一个常量,因为我不应该触摸或修改js文件,因为这些值可能会被其他非技术人员改变。那么这应该行得通。您的具体关注点是什么?也不需要进行同步,这通常不是一个好主意。在这种情况下,什么东西不能使用async?我的建议对您有帮助吗?请分享你的发现
var urlValue;
// --asynchronous
configService.getValue('url').then(function(response) {
urlValue = response.data; // -- success logic
});
console.log('be mindful - I will execute before you get a response');
[...]
getValue: function(key, onSuccess){
$http.get("js/resources/urls.properties").success(function(response){
onSuccess(response);
})