4

I've been looking over and over for an example on how to cancel an ongoing REST-call using Angular's $resource. I haven't found any solution yet, but from the Angular documentation I got the impression that it should be possible.

From the documentation:

Usage: $resource(url[, paramDefaults][, actions]);

One of the actions defined in the documentation:

timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.

Does anyone have a working example showing how to use this timeout action with promise to cancel an ongoing request? Is it possible?

jstensen
  • 157
  • 1
  • 2
  • 9

2 Answers2

3

My code example:

var canceler = {};
$scope.doSomething = function() {
  canceler = $q.defer();
  $http.post('url', data, {timeout: canceler.promise}).
    success(function(data) {
    }).
    error(function() {
    });
};

function cancelPost() {
  canceler.resolve(); //aborts request  
}

}

jstensen
  • 157
  • 1
  • 2
  • 9
1

Yes this is possible. You have to create a defere and set the promise as parameter:

var timeoutPromise = $q.defer();

{timeout: timeoutPromise.promise}

Then you can resolve the promise at any time:

timeoutPromise.resolve(); 

It should also be possible to call $timeout.cancel(timeoutPromise). What should be equal to timeoutPromise.reject().

$timeout $q

michael
  • 16,221
  • 7
  • 55
  • 60
  • 2
    Thanks for your quick reply. You pointed me out in the right direction. However I had troubles appplying the timeout on my $resource which is placed in a factory to be used several times. It seems the timeout configuration can only be initialized once when using this pattern. The way I solved it was moving the $resource out of the service and into the controller to be able to set the timeout with a new promise for each time I call my rest-service. After a while I also decided to change from $resource to $http. – jstensen Jan 22 '14 at 08:49