I have a controller that is attached to a route. The controller constantly polls the server using $timeout
. When the route changes, I need to stop polling, and start it again when the route changes back.
我有一个连接到路线的控制器。控制器使用$ timeout不断轮询服务器。当路线改变时,我需要停止轮询,并在路线改变时再次启动它。
Please help.
Here is my code:
这是我的代码:
(angular
.module('app.controllers', ['ng', 'ngResource'])
.controller('myContr', [
/******/ '$scope', '$resource', '$timeout',
function ($scope, $resource, $timeout) {
function update() {
$resource('my-service').get({}, function (d) {
// ...use data...
$timeout(update, UPDATE_INTERVAL);
});
};
update();
}
])
);
1 个解决方案
#1
3
- Save the return value (a promise) from
$timeout
(to a $scope property). - Register a
$destroy
event handler on your scope. - Call
cancel()
on that $timeout promise when the event handler triggers.
从$ timeout(到$ scope属性)保存返回值(一个promise)。
在您的作用域上注册$ destroy事件处理程序。
当事件处理程序触发时,在$ timeout promise上调用cancel()。
When the route changes back, the controller will get recreated, so your existing code should start up the polling again.
当路由更改回来时,控制器将重新创建,因此现有代码应该再次启动轮询。
#1
3
- Save the return value (a promise) from
$timeout
(to a $scope property). - Register a
$destroy
event handler on your scope. - Call
cancel()
on that $timeout promise when the event handler triggers.
从$ timeout(到$ scope属性)保存返回值(一个promise)。
在您的作用域上注册$ destroy事件处理程序。
当事件处理程序触发时,在$ timeout promise上调用cancel()。
When the route changes back, the controller will get recreated, so your existing code should start up the polling again.
当路由更改回来时,控制器将重新创建,因此现有代码应该再次启动轮询。