如何覆盖angularjs中的$ http对象
问题描述:
我正在使用& http在角度js中进行REST调用。而当我拨打新电话时,我想解除先前的电话。所以我将数据调用包装在服务中,并在控制器中调用服务。我使用全局参数来保存最后的调用对象。所以每当我调用函数getsth()时,它都会用新函数取代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);
}
答
此博文解释了您的使用情况非常好:
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);
};
});
可以添加装饰,或inte rceptor ...完全覆盖对象将是一个非常可怕的想法。 – 2015-04-02 17:23:54
@DanPantry Thant是真的。我决定使用$ http的取消功能。谢谢 – Gabriel 2015-04-02 21:06:59