2014-04-29 19 views
0

我試圖在服務器響應401狀態碼時觸發登錄模式。基於這個指南https://medium.com/opinionated-angularjs/7bbf0346acec我已經創建了一個這樣的狀態碼攔截器。試圖在401服務器響應中觸發用戶界面

// intercept http status codes 
app.config(function ($httpProvider) { 
    $httpProvider.interceptors.push(['$injector', function ($injector) { 
     return $injector.get('AuthInterceptor'); 
    }]); 
}); 

app.factory('AuthInterceptor', function ($rootScope, $q) { 
    return { 
     responseError: function (res) { 
      if (res.status === 401) { 
       console.log('AuthInterceptor says you are not authorized'); 
      } 
      if (res.status === 404) { 
       console.log('AuthInterceptor says this page is not found'); 
      } 
      return $q.reject(res); 
     } 
    }; 
}); 

當我嘗試注入我的AuthInterceptor工廠與$模態我得到一個循環依賴錯誤。從這樣的事情觸發一個$模態的好習慣是什麼?我鏈接的指南使用此AuthInterceptor工廠來廣播'Auth_events',它們只是常量字符串。他們沒有顯示任何超出廣播範圍的auth_event,所以我不明白他們是如何工作的。除了我的主要問題,任何人都可以澄清這些授權事件是做什麼的?

回答

3

由於$modal服務依賴於$http,您將收到循環依賴關係錯誤。這是$http攔截器自身依賴於$http的一個常見問題。幸運的補救措施很簡單:你需要從噴射閥噴射$injector到你的攔截器和檢索$model像這樣:

app.factory('AuthInterceptor', function ($rootScope, $q, $injector) { 
    return { 
     responseError: function (res) { 

      var $modal = $injector.get('$modal'); 

      if (res.status === 401) { 
       //you can use $modal here... 
       console.log('AuthInterceptor says you are not authorized'); 
      } 
      if (res.status === 404) { 
       console.log('AuthInterceptor says this page is not found'); 
      } 
      return $q.reject(res); 
     } 
    }; 
}); 
+0

謝謝你,工作,並給了我一個更好地瞭解正在發生的循環依賴的。你有任何提示檢查模式是否正在打開?有關這個http攔截器的例子。我有一個模態登錄表單。感謝你,只要401狀態碼被攔截,我現在可以打開這個模式。登錄表格本身會在輸入無效憑證時發送401狀態碼,然後將新的登錄模式堆疊在原件上。我該如何避免這種情況? – Constellates

相關問題