So, one of my $angular scopes starts a $http request upon user interaction. That request that take quite a while to run and it can happen that when its promise is resolved, the scope that was used to start the request is already gone.
Now, obviously, because js is a nice language the scope object is still there because it's been captured in the promise handler variable scope so, at worst, what is going to happen is that I am going to update the scope variables even though the scope is entirely unused. However, one of the things that can happen in this handler is this:
$state.go("^");
Now, if the ui-router state that is associated with this scope was still active, this would work fine but when the users get bored, they tend to click around and move back to another state where executing $state.go("^") is not a good idea.
I could:
- In the promise handler, check that the current state is still "the same" before .go("^") (I will skip on what "the same" really means)
- Somehow, make sure that the $http request handlers get canceled when the $scope is destroyed.
Clealy, 1. is... scary. 2. is not too painful enough:
$scope.running_http_request = $http.get(...).then(function (result) {...});
$scope.$on("destroy", function () {
$scope.running_http_request.cancel()
});
(Yes, there is no native cancel method on $http requests but it's not too horrible to add so, I could do this).
Now, all of this is really painful: is there a better way to make sure that if my $scope goes away, whatever was pending with that scope goes away too ?