我有一家工厂,承诺每隔 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());
}])