1

我有以下攔截器:

var interceptor = ['$http', '$q', function ($http, $q) { 
    //... 
}]; 

這產生循環依賴,因爲$http將取決於這個攔截,而這種攔截將取決於$http

我想獲取$http服務,因爲我打算刷新用戶的某些授權令牌,如果我得到401未經授權的響應。

爲此,我必須調用我的OAuth端點並檢索新的令牌。

如何將此服務注入到攔截器中?

我也試過以下選擇:

var interceptor = ['$injector', '$q', function ($injector, $q) { 
    var $http = $injector.get('$http'); 
}] 

但我發現了同樣的錯誤。

這可能嗎?

我不想使用jQuery庫,我希望我的應用程序是純AngularJS,因此$.ajax(...)答案對我無用。

+0

包裹你的噴油器的代碼也許你可以激發關閉事件或調用另一個服務做的工作適合你? – JoseM

回答

2

即使是第二個代碼段也會導致cdep錯誤,因爲攔截器服務將被實例化,並且在構造函數中,您正試圖在此過程中獲取$http,這會導致cdep錯誤。稍後,在實例化攔截器服務後,您需要獲取http服務(或任何注入http的服務)。您可以根據需要輕鬆從$injector中獲得,例如在reponseError上。

var interceptor = ['$injector', '$q', 
    function($injector, $q) { 
     return { 

     responseError: function(rejection) { 
      //Get it on demand or cache it to another variable once you get it. But you dont really need to do that you could get from the injector itself since it is not expensive as service is a singleton. 
      var $http = $injector.get('$http'); 
      //Do something with $http 
      return $q.reject(rejection); 
     } 
     } 
    } 
    ] 
-1

嘗試用匿名函數

var interceptor = ['$injector', '$q', function ($injector, $q) { 
      return function(){ 
       var $http = $injector.get('$http'); 
      } 
    }];