取消有角度的服务承诺 [英] Cancelling an angular service promise
本文介绍了取消有角度的服务承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个执行http请求的控制器.
此请求可能需要2秒钟到4分钟之间的任何时间才能返回一些数据.
我添加了一个按钮,如果搜索需要太长时间才能完成,用户应单击以取消请求.
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.
控制器:
$scope.search = function() {
myFactory.getResults()
.then(function(data) {
// some logic
}, function(error) {
// some logic
});
}
服务:
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;
}
}
}
按钮单击:
$scope.cancelGetResults = function() {
// some code to cancel myFactory.getResults() promise
}
如何实现单击按钮以取消myFactory.getResults()
承诺?
How can I implement a button click to cancel the myFactory.getResults()
promise?
推荐答案
getResult是一项我们正在实施取消的服务.
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;
};
其中,使用url变量代替任何Restful API URL.您可以将其与给定的代码一起使用.
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); };
这篇关于取消有角度的服务承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文