AngularJS:如何阻止请求
是否可以使用angularjs拦截器阻止请求AngularJS:如何阻止请求,angularjs,request,Angularjs,Request,是否可以使用angularjs拦截器阻止请求 $provide.factory('myHttpInterceptor', function($q, someService) { return { 'request': function(config) { // here I'd like to cancel a request depending of some conditions } } }); $httpProvider.interceptors.pu
$provide.factory('myHttpInterceptor', function($q, someService) {
return {
'request': function(config) {
// here I'd like to cancel a request depending of some conditions
}
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
在1.1.5及更高版本中,您可以使用配置对象的“timeout”属性 从: 超时–{number | Promise}–以毫秒为单位的超时,或承诺 解决后应中止请求 简单的例子:
$provide.factory('myHttpInterceptor', function($q, someService) {
return {
'request': function(config) {
var canceler = $q.defer();
config.timeout = canceler.promise;
if (true) {
// Canceling request
canceler.resolve();
}
return config;
}
}
});
$httpProvider.interceptors.push('myHttpInterceptor');
我应用了这种逻辑,这种逻辑是有效的:
$scope.cancelRequest = 0; // initilize taking variable
$scope.searchUser = function() {
$scope.cancelRequest = 0; // initilize taking variable
var opts = {};
$scope.userList = []; //array in witch i store the list
if($scope.searchFrind != ""){ // checking the value of the model is blank or their is some data
opts.limit_size = 10;
ProfileService.searchUser(opts, function(data) { // calling the service which call the http request
if( $scope.cancelRequest == 0 ){ // checking the value of cancelRequest as if the request is late and we doesnot want it then it fall in the else case
angular.forEach(data.data.users,function(user) {
$scope.userList.push(user);
})
}else{ //when the cancelRequest is notequal 0 then this part run
$scope.userList = []; //empty the array
}
});
}else{
$scope.userList = [];
$scope.cancelRequest = 1; //changing the value of cancelRequest to 1 so that the pending http request after completion does not disturb the array or any model
}
};
你能解释一下当(配置)时返回配置| |$q行是什么吗代码>是什么?或者更确切地说:
config
如何计算为false?该行上方的代码假定它是有效的配置对象?您是正确的。它应该是returnconfig
,因为config.timeout=canceler.promise如果config
仍然是未定义的
,则code>将不起作用。我很草率,从旧的拦截器文档中获取了代码,其中只包含行returnconfig | |$q.when(config)代码>并在其上添加了一些逻辑。我会编辑它。谢谢。您仍然在发出一个实际的HTTP请求(并丢弃它的响应,导致无用的服务器负载),这不是OP所希望的。