我有一个承诺的工厂,应该以5秒的间隔从webservice轮询数据。数据将由控制器获取并解析。轮询器是从应用程序启动的。快跑

问题是数据似乎无法从控制器访问,这是为什么?

(只是看着它,我开始怀疑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());


    }])
有帮助吗?

解决方案

问题是线路返回 liveData 在您的服务中,当 $http 电话正在进行中,我会把 liveData 对象围绕一个promise,并在控制器中使用该promise。或者,作为一个穷人的方法,你可以看 liveData 控制器中的对象:

$scope.$watch(liveDataPoller.getData,function(value){
    console.log(value);
},true)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top