启动新控制器时停止 $timeout [英] Stop $timeout when starting new controller
问题描述
我每 2 秒轮询一次我的数据,以使它们在页面上保持更新.我的问题是当我访问另一个页面时超时保持活动状态.访问新页面时如何取消超时?
I'm polling for my data every 2 seconds to keep them updated on the page. My problem is when I visit another page the timeout stays active. How can i cancel my timeout when I visit an new page?
function IndexCtrl($scope, $timeout, RestData) {
$scope.rd = {};
(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$timeout(getRestDataFromServer, 2000);
});
})();
}
//编辑我找到了一个解决方案,但我不确定它是否是一个好的解决方案.当我将超时保存到 $rootScope 时,我可以在所有其他控制器中取消它.
//EDIT I found a solution, but I'm not sure if it's a good one. When i save my timeout to the $rootScope, I can cancel it in all the other controllers.
function IndexCtrl($scope, $rootScope, $timeout, RestData) {
$scope.rd = {};
(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$rootScope.prom = $timeout(getRestDataFromServer, 2000);
});
})();
}
function newPageCtrl($scope, $rootScope, $timeout) {
$timeout.cancel($rootScope.prom);
}
推荐答案
有几个 Angular 事件在路由改变时被广播.您可以使用 $scope.$on
在 IndexCtrl
中监听它们并采取相应的行动:
There are couple of Angular events that are being broadcasted when route is being changed. You can listen for them within the IndexCtrl
using $scope.$on
and act accordingly:
$destroy 事件
var promise = $timeout(getRestDataFromServer, 2000);
...
$scope.$on('$destroy', function(){
$timeout.cancel(promise);
});
$locationChangeStart
var promise = $timeout(getRestDataFromServer, 2000);
...
$scope.$on('$locationChangeStart', function(){
$timeout.cancel(promise);
});
$timeout()
返回一个承诺对象.这个对象可以提供给 $timeout.cancel()
函数来取消超时.
$timeout()
returns a promise object. This object can be supplied to $timeout.cancel()
function to cancel the timeout.
这篇关于启动新控制器时停止 $timeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!