![](/img/trans.png)
[英]How to work with ui.router's $stateChangeStart in angularjs?
[英]Redirection on `$stateChangeStart` with angularJS + ui.router
嘗試將未經身份驗證的用戶重定向到登錄屏幕。
我正在使用ui.route
r和一條指令來檢查登錄的用戶。 但是它沒有按我預期的那樣工作。 在頁面加載之前不檢查它,而我在連續重定向中停留在該頁面上。
路由配置:
//User profile
.state('UserProfile', {
url: "/u/:id",
data: {
restrict: true,
name: "Your Profile",
header: true,
footer: false,
css: true,
transparentHeader: true
},
templateUrl: "app/partials/user/userProfile.html",
controller: "userProfileController"
})
//Login page for not authenticated users
.state('LoginPage', {
url: "/login/",
data: {
restrict: false,
name: "Login",
header: false,
footer: false,
css: false,
transparentHeader: false
},
templateUrl: "app/partials/common/loginPage.html",
controller: "loginController"
})
服務:
.factory('userService', ['$cookies', function($cookies){
var userData = {
isLogged: false,
userId: "",
firstName: "",
profilePic: ""
};
return userData;
}]);
指示:
socialMarkt.directive('checkUser', ['$rootScope', '$state', 'userService', function ($r, $state, userService) {
return {
link: function (scope, elem, attrs, ctrl) {
$r.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
event.preventDefault();
if($state.current.data.restrict){
if(!userService.isLogged){
$state.go('LoginPage');
}
}
});
}
}
}]);
我只是將其添加到一頁進行測試。 因此,如果用戶未登錄,則可以使用$state.go('LoginPage')
重定向到登錄頁面。
我更改了驗證登錄狀態的方式。
我在.run上做
.run(['$rootScope', '$state', 'userService', '$sessionStorage', function($rootScope, $state, userService, $sessionStorage){
$rootScope.$on('$stateChangeStart'
, function(event, toState, toParams, fromState, fromParams) {
//Detecting sessions
if($sessionStorage.userData){
var goodORnot = $sessionStorage.userData.isLogged;
}else{
goodORnot = false;
}
var isAuthenticationRequired = toState.data
&& toState.data.requiresLogin
//&& !userService.isLogged
&& !goodORnot
;
if(isAuthenticationRequired)
{
event.preventDefault();
$state.go('LoginPage');
}
});
}]);
我看到的一個問題是您調用的preventDefault()太早了。 如果狀態不受限制或用戶已登錄,則狀態更改應該順利進行,而您要防止這種情況發生。 event.preventDefault()應該放在$ state.go('loginPage')之前;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.