承诺数据属性不起作用

时间:2014-06-03 12:24:09

标签: angularjs angularjs-factory angular-promise

我有一个承诺应该以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());


    }])

1 个答案:

答案 0 :(得分:1)

问题是当liveData调用正在进行时,您的服务中返回$http行,我会将liveData对象包围在一个承诺中并使用该承诺控制器。或者,作为一种糟糕的勒芒方法,您可以在控制器中观察liveData对象:

$scope.$watch(liveDataPoller.getData,function(value){
    console.log(value);
},true)