我有一个工厂,承诺会每隔5秒轮询一次Web服务中的数据。数据将由控制器提取并解析。轮询程序是从app.run启动的。
问题是似乎无法从控制器访问数据,这是为什么?
(只是通过查看它,我开始怀疑LiveData var是否是线程安全的)
factory('liveDataPoller', ['$http', '$timeout', function($http, $timeout) {
var liveData = {
status: -1,
events: [],
checksum: 0,
serverTime: 0,
calls: 0
};
var poller = function() {
$http.get('/api/getInformation.json')
.then(function(res) {
status = res.statusCode;
if(status < 0) {
// TODO: handle service error
} else {
liveData.events = res.events;
liveData.checksum = res.checksum;
liveData.serverTime = res.serverTime;
}
liveData.status = status;
liveData.calls++;
$timeout(poller, 5000);
});
};
poller();
return {
getData: function() {
return liveData;
}
};
}])
控制器:
angular.module('myApp.controllers', [])
.controller('MainCtrl', ['$rootScope', '$scope', '$timeout', 'liveDataPoller', function($rootScope, $scope, $timeout, liveDataPoller) {
var transformLiveData = function(liveData) {
var liveDataObj = {
serverTime: liveData.serverTime,
checksum: liveData.checksum,
events: [],
calls: liveData.calls
},
events = [],
i;
if(liveData.events) {
for(i = 0; i < liveData.events.length; i++) {
events.push({
id: liveData.events[i].id,
name: liveData.events[i].details[1],
freeText: liveData.events[i].details[2],
});
}
liveDataObj.events = events;
}
return liveDataObj;
}
$rootScope.liveData = transformLiveData(liveDataPoller.getData());
}])
问题是liveData
当$http
调用正在进行时,返回到服务中的行会执行,我会将liveData
对象包装在一个Promise周围,并在控制器中使用该Promise。或者,作为穷人的方法,您可以liveData
在控制器中观察对象:
$scope.$watch(liveDataPoller.getData,function(value){
console.log(value);
},true)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句