Skip to content Skip to sidebar Skip to footer

Cancelling An Angular Service Promise

I have a controller that performs a http request. This request can take anywhere between 2 seconds to 4 minutes to return some data . I have added a button, that users should click

Solution 1:

The question uses deferred antipattern which usually should be avoided, but it fits the cancellation case:

getResults: function(data) {
    var deffered = $q.defer();

    $http.get('someURL', {
        data: {},
        responseType: json
    }).then(deffered.resolve, deferred.reject);

    deffered.promise.cancel = function () {
      deferred.reject('CANCELLED')
    };

    returned deffered.promise;
}

Solution 2:

getResult is a service in which we are implementing cancellation.

getResult = function(){
var deferred = $q.defer();
$http.get(url).success(function(result){
   deffered.resolve(result);
}).error(function(){
deffered.reject('Error is occured!');
});
return deferred.promise;
};

where url variable is used in place of any Restful API url. You can use it with given code.

getResult().then(function (result) { console.log(result); };

Solution 3:

You could use .resolve() method which should be available.

Pass the promise in the controller to the variable.

Create e.g. cancel method which takes the promise as an argument in you factory. Then call this method in the cancelGetResults() function in the controller.

In the cancel method you just call .resolve on the passed promise.

This should actually do.

https://www.bennadel.com/blog/2731-canceling-a-promise-in-angularjs.htm


Post a Comment for "Cancelling An Angular Service Promise"