We needed to cancel angularjs $resource requests but have found that it's not trivial, though $http service has timeout property that allows to pass a promise that aborts a request when resolved.
So, we took a little time and divised a code to be able to cancel such requests.
Consider a sample (nesterovsky-bros/angularjs-api/master/angularjs/cancel-resource.html):
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Cancel resource</title> <style type="text/css"> .ng-cloak { display: none; } </style> <script src="angular.js"></script> <script src="angular-resource.js"></script> <script> angular.module("app", ["ngResource"]). factory( "services", ["$resource", function($resource) { function resolveAction(resolve) // #1 { if (this.params) { this.timeout = this.params.timeout; this.params.timeout = null; } this.then = null; resolve(this); } return $resource( "http://md5.jsontest.com/", {}, { MD5: { method: "GET", params: { text: null }, then: resolveAction // #2 }, }); }]). controller( "Test", ["services", "$q", "$timeout", function(services, $q, $timeout) { this.value = "Sample text"; this.requestTimeout = 100; this.call = function() { var self = this; self.result = services.MD5( { text: self.value, timeout: $q(function(resolve) // #3 { $timeout(resolve, self.requestTimeout); }) }); } }]); </script> </head> <body ng-app="app" ng-controller="Test as test"> <label>Text: <input type="text" ng-model="test.value" /></label><br/> <label>Timeout: <input type="text" ng-model="test.requestTimeout" /></label><br/> <input type="button" value="call" ng-click="test.call()"/> <div ng-bind="test.result.md5"></div> </body> </html>
$resource
config
$http
promise
then
timeout promise
params
In code it looks like this:
resolve
services.MD5()
timeout
That's all. The demo can be found at cancel-resource.html