1
我試圖基於身份驗證重定向用戶,以便在每個路由狀態的解決方案中放置我的服務以檢查身份驗證,以便在此情況下登錄和儀表板。UI-Router在無限循環中解決承諾失敗
.state('login', {
url: "/login",
abstract: true,
templateUrl: '/app/login/login.html'
})
// Default login state
.state('login.index', {
url: "",
templateUrl: "/app/login/views/login.html",
controller: 'LoginController',
controllerAs: 'loginCtrl',
resolve: {
UserAuth: session
}
})
.state('dashboard', {
url: "/dashboard",
abstract: true,
templateUrl: '/app/dashboard/dashboard.html',
resolve: {
UserAuth: session
}
})
// Default dashboard state
.state('dashboard.index', {
url: "",
templateUrl: '/app/dashboard/views/page1.html',
controller: 'Page1Controller',
controllerAs: 'page1Ctrl',
resolve: {
UserAuth: session
}
})
// with multiple states like the child route above...
在我的.config路由我還設置了會話使用以上,這對承諾的成功或生存的會話$ state.go到儀表盤,否則就承諾未能$ state.go登錄。
.config(function($stateProvider, $urlRouterProvider) {
var session = ['$q', '$location', '$state', 'SessionService',
function($q, $location, $state, SessionService) {
return SessionService.session()
.then(function(session) {
// Check location path as $state is not resolved yet
var location = $location.path();
/**
* Check user authentication to dashboard and handle
* state change if session already exists
*/
if(location.indexOf('login') === 1) {
// Redirect to default dashboard view
$state.go('dashboard.index');
}
}, function(error) {
// Check location path as $state is not resolved yet
var location = $location.path();
/**
* Check for unauthorized access to dashboard and handle
* state change if not located on login view
*/
if(location.indexOf('dashboard') === 1) {
// Redirect to default login view
$state.go('login.index');
}
// Don't propagate error since it has been handled and it prevents page
// return $q.reject(error);
});
}];
但是,它通過403錯誤的無限循環中運行時,我讓會話超時,這是承諾失敗了正確的服務器響應。它輸入if語句,並運行$ state.go('login.index'),但保持循環,並且永遠不會用登錄替換狀態。任何人都可以看到我做錯了什麼?在除會話超時之外的所有情況下工作,然後不重定向。
那麼我可以想像這是怎麼回事錯了,login.index途徑解決無論你SessionService返回時,它返回的成功,你的後臺登錄路由可能不進行身份驗證,它重定向到dashboard.index,認證失敗,重定向到login.index,沖洗並重復。只是一個猜測,但這可能是怎麼回事.. – jfornoff 2014-10-16 20:39:47
是的,我已經改變$ state.go $ location.path('/登錄')$ location.replace();它似乎糾正它。我認爲不會返回$ q.reject表示錯誤已經被處理,並且允許路徑解決,但是在返回之前注意到它不會在$ state.go中出現。感謝您成爲一名聽衆。 – mtpultz 2014-10-16 21:49:06
很高興能幫到你!如果您有興趣,很多人都會使用HTTP攔截器。可能有一些示例代碼也掛在某處;-) – jfornoff 2014-10-16 21:53:12