gpt4 book ai didi

angularjs - 路由更改后销毁 Angular $http 成功/错误片段

转载 作者:可可西里 更新时间:2023-11-01 17:36:25 24 4
gpt4 key购买 nike

问题可以在这里看到:http://embed.plnkr.co/Qcw1YA/

我运行 route1 并且我有一个 $timeout 函数。我迅速切换到 route2,然后 route1 的延迟代码出现了。我想销毁在 $timeout 函数中运行的任何代码,在实际情况下,它是一个 $http 服务请求,并显示来自先前路由的错误消息。

最佳答案

这里的解决方案是:自己清洁。

Best Practices

...

Add teardown code to controllers and directives
Controller and directives emit an event right before they are destroyed. This is where you are given the opportunity to tear down your plugins and listeners and pretty much perform garbage collection.

Subscribe to the $scope.$on('$destroy', ...) event

所以,而不是这个(有 a updated 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 已取消...它会稍后或早些来自服务器...

关键是,如果有任何可能在响应到来时触发的幽灵操作(在 .then() 内部),我们应该清除它们或检查是否状态还没有消失...

查一下here

关于angularjs - 路由更改后销毁 Angular $http 成功/错误片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30256387/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com