1

the issue can be seen here: http://embed.plnkr.co/Qcw1YA/

I run route1 and I have a $timeout function. I quickly switch to route2, then the delayed code from route1 shows up. I want to destroy any code running in the $timeout function, which in a real case scenario is an $http service request and shows error messages from previous routes.

Alex Arvanitidis
  • 4,403
  • 6
  • 26
  • 36

2 Answers2

1

Solution here is: DO clean after ourselves.

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

So, instead of this (there is a updated plunker)

controller: function($timeout) {
    $timeout(function() {
      alert("Hey I'm message from route 1!");
    }, 5000)
}

we should do this:

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')
    });
}

Not saying - that $http has cancel... it will simply later or sooner come from server...

The point is, if there are any ghost actions which could be triggered when repsonse comes (inside of .then()) we should either clear them or check if the state has not gone...

Check it here

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Thanks! For better documentation, the answer to cancelling an $http request in angular is here: http://stackoverflow.com/questions/13928057/how-to-cancel-an-http-request-in-angularjs/17328336#17328336 – Alex Arvanitidis May 15 '15 at 10:55
  • Great if that helped anyhow, sir! Enjoy `UI-Router`, awesome tool ;) – Radim Köhler May 15 '15 at 11:13
0

$timeout service in AngularJS returns a Promise that can be destroyed by calling cancel method.

//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()
shershen
  • 9,875
  • 11
  • 39
  • 60