2013-10-31 14 views
7

क्या कोणीय इंटरसेप्टर्स का उपयोग करके अनुरोध को रोकना संभव है?कोणीयजेएस: अनुरोध को कैसे रोकें

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

उत्तर

16

1.1.5 में और बाद में आप कॉन्फ़िगरेशन ऑब्जेक्ट की 'टाइमआउट' प्रॉपर्टी का उपयोग कर सकते हैं।

documentation से:

टाइमआउट - {संख्या | वादा} - मिलीसेकेंड में समय समाप्त, या वादा करता हूँ कि हल हो जाने पर अनुरोध निरस्त कर देना चाहिए।

सरल उदाहरण:

$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

आप क्या लाइन 'वापसी config समझाने कृपया सकते हैं || $ q.when (config); 'करता है? या इसके बजाय: 'कॉन्फ़िगरेशन' को गलत तरीके से कैसे मूल्यांकन किया जा सकता है - उस पंक्ति के ऊपर वाला कोड मानता है कि यह एक मान्य कॉन्फ़िगरेशन ऑब्जेक्ट है? –

+1

आप सही हैं। यह 'config.timeout = canceler.promise' के बाद से 'रिटर्न कॉन्फ़िगरेशन' होना चाहिए; 'अगर कॉन्फ़िगरेशन' अपरिभाषित 'है तो वैसे भी काम नहीं करेगा। मैं मैला था और पुराने इंटरसेप्टर दस्तावेज से कोड ले लिया, जिसमें केवल 'रिटर्न कॉन्फ़िगरेशन || पंक्ति शामिल है $ q.when (config); 'और इसके ऊपर कुछ तर्क जोड़ा गया। मैं इसे संपादित करूंगा। धन्यवाद। – tasseKATT

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

आप अभी भी एक वास्तविक HTTP अनुरोध कर रहे हैं (और इसकी प्रतिक्रिया को छोड़कर, जिसके परिणामस्वरूप बेकार सर्वर लोड होता है), जो ओपी द्वारा वांछित नहीं है। –

संबंधित मुद्दे