Cancelling an angular service promise

僤鯓⒐⒋嵵緔 提交于 2019-12-25 09:17:41

问题


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?


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



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



回答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



来源:https://stackoverflow.com/questions/41125333/cancelling-an-angular-service-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!