簡體   English   中英

將$ http服務注入$ http攔截器?

[英]Injecting $http service into $http interceptor?

我有以下攔截器:

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(...)答案對我沒有用。

即使第二個代碼段也會導致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);
        }
      }
    }
  ]

嘗試在匿名函數中包裝您的注射器代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM