2013-10-31 6 views
7

Angularjs interceptors kullanarak bir talebi önlemek mümkün mü?AngularJS: Bir istek nasıl engellenir?

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

cevap

16

1.1.5 ve sonrasında yapılandırma nesnesinin 'zaman aşımı' özelliğini kullanabilirsiniz. documentation itibaren

:

zaman aşımı - {sayı | Promise} - milisaniye cinsinden zaman aşımı veya çözüldüğünde isteği iptal gerektiğini veriyorum.

Basit bir örnek:

$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

ne hat 'dönüş yapılandırma açıklayabilir misiniz || $ q.when (config); 'yapar? Ya da daha ziyade: false olarak nasıl konfigüre edilebileceğini - bu satırın üzerindeki kod geçerli bir yapılandırma nesnesi olduğunu varsayar? –

+1

Siz haktasınız. "Config", "config \" undefined "ise, config.timeout = canceler.promise; Özensiz kaldım ve kodu sadece 'return config || satırını içeren eski önleyici belgelerden aldım. $ q.when (config); 've bunun üzerinde bir mantık ekledi. Onu düzenleyeceğim. Teşekkür ederim. – tasseKATT

-2

Ben çalışıyor bu mantığı geçerlidir:

$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

Hala OP tarafından istenmeyen, gerçek bir HTTP isteği yapıyorsunuz (ve bunun cevabını ortadan kaldırarak, faydasız sunucu yüküne neden oluyor). –