데이터 속성이 작동하지 않는 약속
-
21-12-2019 - |
문제
저는 5 초 간격으로 웹 서비스에서 데이터를 폴링 할 수있는 약속이있는 공장이 있습니다.데이터는 컨트롤러에 의해 가져와 구문 분석되어야합니다.폴러는 app.run에서 시작됩니다.
문제는 데이터가 컨트롤러에서 액세스 할 수없는 것처럼 보이는 것처럼 보입니다.
(LiveData var가 threadsafe인지 궁금해하기 시작합니다)
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());
}])
. 해결책
PergenaCodiceTag 코드 호출이 진행 중일 때 서비스의 liveData
를 반환하는 것은 Promise 및 Controller에서 약속과 함께 Promise 및 Work에서 $http
객체를 감쌀 것입니다.또는 가난한 사람 접근 방식으로 컨트롤러에서 liveData
객체를 볼 수 있습니다.
$scope.$watch(liveDataPoller.getData,function(value){
console.log(value);
},true)
. 제휴하지 않습니다 StackOverflow