路由更改后销毁 angular $http success/error 片段

Destroy angular $http success/error snippets after route change

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

我 运行 route1 并且我有一个 $timeout 函数。我迅速切换到 route2,然后 route1 的延迟代码出现了。我想销毁 $timeout 函数中的任何代码 运行ning,在实际情况下它是一个 $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

$timeout service in AngularJS returns 一个 Promise 可以通过调用 cancel 方法销毁。

//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()