fra*_*erm 27 angularjs angularjs-service
我每隔2秒轮询一次我的数据,以便在页面上更新它们.我的问题是当我访问另一个页面时,超时保持活动状态.当我访问新页面时,如何取消暂停?
function IndexCtrl($scope, $timeout, RestData) {
$scope.rd = {};
(function getRestDataFromServer() {
RestData.query(function(data){
$scope.rd = data;
$timeout(getRestDataFromServer, 2000);
});
})();
}
Run Code Online (Sandbox Code Playgroud)
//编辑我找到了一个解决方案,但我不确定它是不是一个好的解决方案.当我将超时保存到$ rootScope时,我可以在所有其他控制器中取消它.
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);
}
Run Code Online (Sandbox Code Playgroud)
Ste*_*wie 64
当路线被改变时,有几个Angular事件正在被广播.您可以在IndexCtrl使用中收听它们$scope.$on并采取相应措施:
$ destroy事件
var promise = $timeout(getRestDataFromServer, 2000);
...
$scope.$on('$destroy', function(){
$timeout.cancel(promise);
});
Run Code Online (Sandbox Code Playgroud)
$ locationChangeStart
var promise = $timeout(getRestDataFromServer, 2000);
...
$scope.$on('$locationChangeStart', function(){
$timeout.cancel(promise);
});
Run Code Online (Sandbox Code Playgroud)
$timeout()返回一个promise对象.可以提供此对象$timeout.cancel()以取消超时.
Eri*_*ton 15
Stewie的答案是完美的.我只是想分享这个简单的帮助函数,而不是$timeout直接使用,所以我再也不用考虑这个问题了:
function setTimeout(scope, fn, delay) {
var promise = $timeout(fn, delay);
var deregister = scope.$on('$destroy', function() {
$timeout.cancel(promise);
});
promise.then(deregister, deregister);
}
Run Code Online (Sandbox Code Playgroud)
我将此函数添加到一个名为的服务中miscUtils,我注入该服务而不是注入$timeout.然后,例如,创建一个每30秒运行一次的"更新"函数,直到$scope被销毁:
update();
function update() {
// do the actual updating here
miscUtils.setTimeout($scope, update, 30000);
}
Run Code Online (Sandbox Code Playgroud)
编辑那些对正在发生的事情感到困惑的人deregister:
此函数注册$destroy事件的侦听器,但一旦超时完成,就不再需要了; 不再有超时取消.scope.$on返回一个函数,在调用时,取消注册该侦听器.因此,promise.then(deregister)一旦超时完成,就会清除不再需要的侦听器.