取消 Angular 服务承诺 [英] Cancelling an angular service promise
本文介绍了取消 Angular 服务承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个执行 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); };
这篇关于取消 Angular 服务承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文