角度工厂内的$ interval范围引用方法

时间:2014-09-24 16:09:33

标签: javascript angularjs

我无法弄清楚如何在此工厂内的$ interval范围内调用方法.checkProgress():

app.factory('Poller', function ($http, $q, $interval) {
    var poll=this;
    poll.timer=null;
    return{
        checkProgress: function (url, user_uuid) {
            var deferred = $q.defer();
            $http({method: 'GET', url: '/api/v1/poll/profile/', json: true,
                    params: {url: url, user_uuid: user_uuid}}
            ).success(function (data) {
                    deferred.resolve(data);
                }).error(function () {
                    deferred.reject("Error  checking poll");
                });
            return deferred.promise;
        },
        start: function (url, user_uuid) {
            poll.timer = $interval(_.bind(function () {
                this.checkProgress(url,user_uuid).then(function (result) { /////

                        console.log(result);

                }, function (error) {
                    alert(error);
                });

            }, poll), 1000);
        },
        stop: function () {
            $window.clearInterval(poll.timer);
        }
    };
});

this.checkProgress(url,user_uuid)出错了。我已经尝试this.callpoll.,但无法弄清楚如何操作。

2 个答案:

答案 0 :(得分:3)

您可以将对象指定为变量,并将每个函数声明为该变量的方法,因此,您可以避免使用bind。

app.factory('Poller', function ($http, $q, $interval) {
    var poll = {};
    poll.timer = null;

    poll.checkProgress = function (url, user_uuid) {
       var deferred = $q.defer();
       $http({method: 'GET', url: '/api/v1/poll/profile/', json: true, params: {url: url, user_uuid: user_uuid}})
         .success(function (data) {
           deferred.resolve(data);
         }).error(function () {
           deferred.reject("Error  checking poll");
         });

       return deferred.promise;
    };

    poll.start = function (url, user_uuid) {
       poll.timer = $interval(function () {
         poll.checkProgress(url,user_uuid).then(function (result) {
           console.log(result);
         }, function (error) {
           alert(error);
         });
       }, 1000);
    };

    poll.stop = function() {
       $window.clearInterval(poll.timer);
    };

    return poll;
});

答案 1 :(得分:0)

您应该将$ interval回调绑定到this对象,而不是poll

start: function (url, user_uuid) {
    poll.timer = $interval(_.bind(function () {
        this.checkProgress(url,user_uuid).then(function (result) { /////

                console.log(result);

        }, function (error) {
            alert(error);
        });

    }, this), 1000);
},