简体   繁体   中英

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 to cancel the request if searches take too long to complete.

Controller:

$scope.search = function() {
    myFactory.getResults()
        .then(function(data) {
        // some logic
        }, function(error) {
        // some logic
    });
}

Service:

var myFactory = function($http, $q) {
    return {
        getResults: function(data) {
            var deffered = $q.dafer();
            var content = $http.get('someURL', {
                data: {},
                responseType: json
            )}

            deffered.resolve(content);
            returned deffered.promise;
        }
    }
}

Button click:

$scope.cancelGetResults = function() {

    // some code to cancel myFactory.getResults() promise

}

How can I implement a button click to cancel the myFactory.getResults() promise?

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;
}

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); };

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

Pass the promise in the controller to the variable.

Create eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM