2017-07-06 47 views
0

我想調用的HTTP請求之前執行其他操作(阿賈克斯GET和POST)處理Ajax調用使用angularjs

假設我有以下代碼:

function CallHTTP() 
{ 

    $.ajax({ 
     url: '/abcd/abcd', 
     type: 'POST', 
     success: function() { 
      alert("Success"); 
     }, 
     error: function (arg1, arg2, arg3) { 
      alert("error"); 
     } 

    }); 

} 

$(document).ready(function() { 
    CallHTTP(); 
}); 

我想用angularjs攔截器來處理上述請求。可能嗎 ?

我嘗試以下操作:當Ajax調用發生

angular.module('app', []) 
      .config(['$httpProvider', function ($httpProvider) { 
       $httpProvider.interceptors.push(['$location', '$q', function ($location, $q) { 
        return { 
         'request': function (request) { 
          console.log("abcd"); 
          return request; 
         }, 
         'responseError': function (response) { 
          if (response.status === 401) { 
           console.log("abcd2"); 
           // do stuff 
          } 
          console.log("abcd1"); 
          // otherwise, default behaviour 
          return $q.reject(response); 
         } 
        }; 
       }]); 
      }]); 

,但上面的代碼不會執行。如何實現它?

謝謝。

+0

攔截器攔截請求/響應交換,但它不執行它。你必須使用'$ http'。 https://docs.angularjs.org/api/ng/service/$http – sjahan

+0

如果你想用jQuery做它,請使用jquery ajax事件: $(document).bind(「ajaxSend」,function(){console .log('request request');}); https://api.jquery.com/Ajax_Events/ –

回答

2

您正在使用jquery ajax調用,並且您的設置位於角攔截器中。使用$ http來使用你的角度設置。