2013-10-31 23 views
7

Có thể ngăn chặn một yêu cầu bằng cách sử dụng máy bay đánh chặn góc?AngularJS: Làm thế nào để ngăn chặn một yêu cầu

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

Trả lời

16

Trong 1.1.5 và sau đó bạn có thể sử dụng thuộc tính 'timeout' của đối tượng cấu hình.

Từ documentation:

timeout - {số | Promise} - thời gian chờ trong mili giây, hoặc hứa rằng nên hủy bỏ yêu cầu khi giải quyết.

đơn giản ví dụ:

$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'); 
+0

Ông có thể giải thích những gì dòng 'trở lại cấu hình || $ q.when (config); 'không? Hay đúng hơn: làm thế nào 'config' có thể đánh giá sai - mã trên dòng đó giả định rằng nó là một đối tượng cấu hình hợp lệ? –

+1

Bạn chính xác. Nó chỉ nên là 'return config', vì' config.timeout = canceler.promise; 'sẽ không hoạt động nếu' config' là 'undefined'. Tôi đã cẩu thả và lấy mã từ tài liệu đánh chặn cũ, chỉ chứa dòng 'return config || $ q.when (config); 'và thêm một số logic ở trên nó. Tôi sẽ chỉnh sửa nó. Cảm ơn bạn. – tasseKATT

-2

tôi áp dụng logic này mà đang làm việc:

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

Bạn vẫn đang thực hiện một yêu cầu HTTP thực tế (và loại bỏ phản hồi của nó, dẫn đến tải máy chủ vô ích), điều này không được OP mong muốn. –

Các vấn đề liên quan