AngularJS:如何阻止请求

时间:2013-10-31 16:11:01

标签: 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.push('myHttpInterceptor');

2 个答案:

答案 0 :(得分:16)

在1.1.5及更高版本中,您可以使用配置对象的'timeout'属性。

来自documentation

  

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');

答案 1 :(得分:-2)

我应用这个有效的逻辑:

$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
    }
};