2014-09-22 56 views
8

我有簡單的API和授權點手柄角401個迴應

當我請求API,我收到了401如果令牌是無效的(令牌失去有效性過去五分鐘)。

我知道我可以攔截401例如與

app.factory("HttpErrorInterceptorModule", ["$q", "$rootScope", "$location", 
    function($q, $rootScope, $location) { 
     var success = function(response) { 
      // pass through 
      return response; 
     }, 
      error = function(response) { 
       if(response.status === 401) { 
        // dostuff 
       } 

       return $q.reject(response); 
      }; 

     return function(httpPromise) { 
      return httpPromise.then(success, error); 
     }; 
    } 
]).config(["$httpProvider", 
    function($httpProvider) { 
     $httpProvider.responseInterceptors.push("HttpErrorInterceptorModule"); 
    } 
]); 

,但我想捕捉和排隊的請求並顯示一個登錄表單,如果是,則成功改變令牌(這是一個頭),並再次執行請求

回答

6

你可以用另一種方式使用$ httpInterceptor。如果您想要在用戶登錄後將用戶重定向到用戶實際失敗的頁面,則需要在某些服務中緩存失敗的請求,然後在登錄後將某個用戶重定向到某處(我的邏輯連接到您的登錄信息)。

但是你可能需要有一些測試終點,以防止無限制地訪問你的控制器,你可能想使用決心https://thinkster.io/egghead/resolve/ 因此,在這種情況下,您會收到限制訪問proctedted點,但不給你的頁面連接錯誤。

爲了解決這個問題,我使用標記參數(或標題)來找出登錄後我應該重定向用戶的位置。

這裏是你的httpInterceptor的例子。

angular.factory('httpInterceptor', function ($q, $rootScope, $log, someService) { 
    return { 
     request: function (config) { 
      return config || $q.when(config) 
     }, 
     response: function (response) { 
      return response || $q.when(response); 
     }, 
     responseError: function (response) { 
      if (response.status === 401) { 
       //here I preserve login page 
       someService 
        .setRestrictedPageBeforeLogin(
          extractPreservedInfoAboutPage(response) 
        ) 
       $rootScope.$broadcast('error') 
      } 
      return $q.reject(response); 
     } 
    }; 
}) 
.config(function ($httpProvider) { 
    $httpProvider.interceptors.push('httpInterceptor'); 
}); 
+0

請問您可以添加解釋嗎?以及如何排隊請求 – rkmax 2014-09-22 16:49:42

+0

關於請求的隊列我會把它們放到緩存中,一些對象失敗請求,然後重定向,然後成功登錄後檢索。我會在15分鐘內解決答案。 – Artemis 2014-09-22 16:59:52

+0

如果我在'request'函數中存儲'configs.push(config)'每個配置並在'response'函數'configs.pop()'中彈出,我如何識別每個響應屬於請求? – rkmax 2014-09-22 17:38:04

2

角HTTP的身份驗證模塊提供攔截請求和queques他們重新給他們後,一旦用戶登錄的服務。

此服務火災也是這些事件的下面,所以你可以聽他們和決定如何在屏幕上顯示

  • 事件:AUTH-loginRequired
  • 事件:AUTH-loginCancelled
  • 事件:AUT-loginConfirmed

看代碼。它只有幾行代碼

https://github.com/witoldsz/angular-http-auth