可以在这里看到问题:http://embed.plnkr.co/qcw1ya/
我运行Route1,并且我有一个$超时功能。我迅速切换到Route2,然后从Route1中显示了延迟代码。我想销毁$超时功能中运行的任何代码,在实际情况下,该代码是$ HTTP服务请求,并显示了以前路由的错误消息。
解决方案是:自行干净。
最佳实践
...
将拆卸代码添加到控制器和指令
控制器和指示在被摧毁之前就发出了事件。在这里,您有机会拆除插件和听众并几乎执行垃圾收集。
Subscribe to the $scope.$on('$destroy', ...) event
所以,而不是这个(有一个更新的plunker)
controller: function($timeout) {
$timeout(function() {
alert("Hey I'm message from route 1!");
}, 5000)
}
我们应该这样做:
controller: function($scope, $timeout) {
var removeTimer = $timeout(function() {
alert("Hey I'm message from route 1!");
}, 5000)
$scope.$on('$destroy', function(){
$timeout.cancel(removeTimer);
console.log('all cleared')
});
}
不说 - $ http已取消...它将在以后或更早来自服务器...
重点是,如果有任何幽灵动作可以触发时,请在repsonse到来时(在 .then()
中),我们应该清除它们或检查状态是否没有消失... p>在此处检查
$ timeout Service在AngularJS中返回可以通过调用cancel
方法破坏的Promise
。
//save the link to a promise
$rootScope.dataRequestPromise = $timeout(function() {
alert("Hey I'm message from route 1!");
}, 5000);
//resolve a promise
$rootScope.dataRequestPromise.cancel()