How to cancel the current REST call using Angular $ resource?

I looked over and over again an example of how to cancel the current REST call using the Angular $ resource. I haven't found a solution yet, but from the Angular documentation I got the impression that this 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 a promise that should interrupt the request when resolving it.

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

+4
source share
2 answers

Yes it is possible. You must create a respite and set the promise as a parameter:

var timeoutPromise = $q.defer();

{timeout: timeoutPromise.promise}

You can then resolve the promise at any time:

timeoutPromise.resolve(); 

You can also call $timeout.cancel(timeoutPromise). What should be equal timeoutPromise.reject().

$timeout $

+1
source

My sample code is:

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  
}

}

+3
source

All Articles