3

I'm trying to write an angularJS service for long polling in my application, using $http.

Here's my code :

app.factory('Poller', function($http, $timeout){
    var poll = function(http, tick){
        http.then(function(r){
            $timeout(poll, tick);
            return r.data;
        });
    };

    return{
        poll: poll
    };
});

The basic idea would be to inject this service whenever I need polling on a $http call. I'm using it inside a controller :

app.controller('myCtrl', function($scope, $http, Poller){
    $scope.polledVar = Poller.poll($http.get('api/getVar'), 1000);
});

When using this code I get the following error :

TypeError: Cannot call method 'then' of undefined
4

2 回答 2

6

即使我不理解这里的设计(overhead design imo)也是这样:

app.factory('Poller', function($http, $timeout,$q){
                var poll = function(http, tick){
                   return http.then(function(r){
                        var deferred = $q.defer();
                        $timeout(function(){
                            deferred.resolve(r);   
                        }, tick);
                        return deferred.promise;
                    });
                };

                return{
                    poll: poll
                };
            });

您可以简单地传递 URL,例如 Poller.poll('api/getVar', 1000);

更新

只是玩玩:)并关注https://stackoverflow.com/a/16520050/356380

var app = angular.module('myModule', []);

            app.factory('Poller', function($http,$q){
               return {
                    poll : function(api){
                        var deferred = $q.defer();
                        $http.get(api).then(function (response) {
                                deferred.resolve(response.data);
                        });
                        return deferred.promise;
                    }

                }
            });
            app.controller('myCtrl', function($scope, $http,$filter ,Poller){
                //Just to start
                $scope.myts = Poller.poll('mytest.php');
                $scope.mydate = $scope.myts.then(function(data){
                    return $filter('date')(data,'yyyy-MM-dd HH:mm:ss Z'); 
                }); 
                var Repeater = function () {
                    $scope.$apply(function () {
                        $scope.myts = Poller.poll('mytest.php');
                        $scope.mydate = $scope.myts.then(function(data){
                            return $filter('date')(data,'yyyy-MM-dd HH:mm:ss Z'); 
                        });
                    });
                };
                var timer = setInterval(Repeater, 1000);             
           });

我的测试.php

echo time()*1000;
于 2013-10-03T09:25:29.023 回答
3

$interval simplifies this a good bit in 1.2+ versions of AngularJs. The video below shows how to use it.

https://www.youtube.com/watch?v=jFxPFgGaEqk

于 2014-07-25T11:52:11.153 回答