简体   繁体   English

取消有角度的服务承诺

[英]Cancelling an angular service promise

I have a controller that performs a http request. 我有一个执行http请求的控制器。
This request can take anywhere between 2 seconds to 4 minutes to return some data . 该请求可能需要2秒钟到4分钟之间的任何时间才能返回一些数据。
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? 如何实现按钮单击以取消myFactory.getResults()承诺?

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是一项我们正在实施取消的服务。

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. 其中使用url变量代替任何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. 您可以使用.resolve()方法,该方法应该可用。

Pass the promise in the controller to the variable. 将控制器中的promise传递给变量。

Create eg cancel method which takes the promise as an argument in you factory. 创建例如cancel方法,该方法在工厂中将promise作为参数。 Then call this method in the cancelGetResults() function in the controller. 然后在控制器的cancelGetResults()函数中调用此方法。

In the cancel method you just call .resolve on the passed promise. 在cancel方法中,您只需对传递的promise调用.resolve即可。

This should actually do. 实际上应该这样做。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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