2014-09-24 38 views
2

內部方法我不能找出如何調用該方法.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.,但無法弄清楚如何去做。

回答

3

您可以分配對象作爲一個變量,而不是和聲明都充當該變量的方法,因此,您避免使用綁定。

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; 
}); 
+0

真棒,這工作。謝謝。現在明顯地顯示給我。 :) – metalaureate 2014-09-24 17:43:47

0

你應該$區間回調綁定到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); 
}, 
+0

不幸的是,同樣的問題 – metalaureate 2014-09-24 17:43:19