1

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


    }])
4

1 回答 1

1

问题是liveData在调用过程中执行的服务中返回的行$http,我会将liveData对象包装在一个承诺周围并在控制器中使用该承诺。或者,作为一个穷人的方法,你可以liveData在你的控制器中观察对象:

$scope.$watch(liveDataPoller.getData,function(value){
    console.log(value);
},true)
于 2014-06-03T12:33:44.033 回答