我在角度js中使用& http来进行REST调用。当我拨打新电话时,我想解雇之前的电话。所以我将数据调用包装在服务中并在控制器中调用服务。我使用全局参数来保存最后一个调用对象。因此,每当我调用函数getsth()时,它都将用新函数替换lastcall。但是当我调试时,它确实用新的替换了lastcall,但之前仍然触发了。一个解决方案是取消之前的呼叫,我尝试了它的工作原理。但我的问题是我可以覆盖$ http对象,以便我不必处理它。感谢
控制器:
var lastCall;
$scope.getsth = function(){
lastcall = service.datacall();
lastcall.then()
}
服务:
service.datacall = function(){
var promises = [];
promises.push($http({url:method...}).then(function))
return $q.all(promises);
}
答案 0 :(得分:0)
这篇博文很好地解释了你的用例:
http://odetocode.com/blogs/scott/archive/2014/04/24/canceling-http-requests-in-angularjs.aspx
app.factory("movies", function($http, $q){
var getById = function(id){
var canceller = $q.defer();
var cancel = function(reason){
canceller.resolve(reason);
};
var promise =
$http.get("/api/movies/slow/" + id, { timeout: canceller.promise})
.then(function(response){
return response.data;
});
return {
promise: promise,
cancel: cancel
};
};
return {
getById: getById
};
});
app.controller("mainController", function($scope, movies) {
$scope.movies = [];
$scope.requests = [];
$scope.id = 1;
$scope.start = function(){
var request = movies.getById($scope.id++);
$scope.requests.push(request);
request.promise.then(function(movie){
$scope.movies.push(movie);
clearRequest(request);
}, function(reason){
console.log(reason);
});
};
$scope.cancel = function(request){
request.cancel("User cancelled");
clearRequest(request);
};
var clearRequest = function(request){
$scope.requests.splice($scope.requests.indexOf(request), 1);
};
});