重定向所有路线登录如果没有认证 [英] Redirect on all routes to login if not authenticated
问题描述
我怎样才能重定向到登录页面,如果有人试图打任何其他路由时不需要进行验证吗?是否有一个最佳的方式AngularJS做到这一点?
How can I redirect to the login page if someone tries to hit any other route when they are not authenticated? Is there a "best" way to do this in AngularJS?
似乎是一个常见的问题,但我似乎无法找到一个方法来做到这一点。预先感谢您的帮助。
Seems like a common problem but I can't seem to find a way to do this. Thank you in advance for your help.
推荐答案
要做到这一点,最好的办法就是建立一个$ routeChangeStart监听器检查的authProvider'的服务功能来验证是否存在登录的用户在我们的'app.js'或在一个单独的文件:
The best way to do this is to set up a '$routeChangeStart' listener which checks an 'authProvider' service function to verify that there is a user logged in. In our 'app.js' or in a separate file:
angular.module('myApp')
.run(['$rootScope', '$location', 'authProvider', function ($rootScope, $location, authProvider) {
$rootScope.$on('$routeChangeStart', function (event) {
if (!authProvider.isLoggedIn()) {
console.log('DENY : Redirecting to Login');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
}
});
}])
那么对于我们的'authProvider服务:
Then for our 'authProvider' service:
angular.module('myApp')
.factory('authProvider', function() {
var user;
return {
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
};
});
该溶液从这里堆栈溢出的答案,我不能在此刻找到拍摄。如果有人恰好是人,请让我知道,我会引用你的答案!
This solution was taken from an answer here on stack overflow which I can't find at the moment. If anyone happens to be the the person please let me know and I will cite your answer!
这篇关于重定向所有路线登录如果没有认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!