2017-03-01 121 views
1

我正在嘗試使autenticate-interptor。核心思想很簡單:當服務器請求失敗時,我們必須通過http-auth登錄用戶。代碼如下所示:

(function() { 
    'use strict'; 

    angular 
    .module('app.authentication') 
    .factory('AuthenticationInterceptor', ['$q', '$injector', '$location', 'Session', 

    function AuthenticationInterceptor($location, $q, $injector, Session) { 
    return { 
     request: function(config) { 
     var currentUser = Session.currentUser(); 

     if (!currentUser || !currentUser.id) { 
      if ($location.path() !== '/login') { $location.path('/login'); } 
     } 

     return config; 
     }, 
     responseError: function(response) { 
     if (response.status === 401 || response.status === 403) { 
      var $http = $injector.get('$http'); 

      Session.destroy(); 

      $location.path('/login'); 
     } 
     return $q.reject(response); 
     } 
    }; 
    } 

    ]); 

})(); 

我需要這個var $http = $injector.get('$http');這裏,因爲circullar注射錯誤的。但是,當我使用該模塊,我得到錯誤TypeError: $injector.get is not a function

那麼,我怎麼可以在這裏注入$ http?

回答

2

注入順序與數組中的字符串不匹配。

angular 
    .module('app.authentication') 
    .factory('AuthenticationInterceptor', ['$q', '$injector', '$location', 'Session', 
    function AuthenticationInterceptor($location, $q, $injector, Session) { 

你告訴角度注入$位置服務作爲第三個參數AuthenticationInterceptor服務,但您使用的是第三個參數,就好像它是$注射器。將您的代碼更改爲以下內容:

angular 
    .module('app.authentication') 
    .factory('AuthenticationInterceptor', ['$location', '$q', '$injector', 'Session', 
    function AuthenticationInterceptor($location, $q, $injector, Session) { 
+0

謝謝,此問題修正了錯誤! –

+0

np - 請upvote /接受一個或兩個答案。看起來我們都同時回答,基本上有相同的答案。 –

+0

對不起,我不能接受更多的9分鐘的答案) –

0
'$q', '$injector', '$location', 'Session' 
$location, $q, $injector, Session 

您沒有推測過相同的順序。

幫你一個忙,並用ng-annotate再也不會有這個bug。