我正在尝试使用angular JS实现基本登录,注销功能,在成功登录后,只有My header必须出现。 一旦用户登录,直到他退出,如果他试图直接访问登录路线,它应该重定向到仪表板。
如何实现这一目标?我在这件事上需要帮助。 我有存储在cookie中的访问令牌。这将告诉我们用户是否登录.. 如果登录..我的路线不应该导致登录路线。
作为参考我正在添加路线代码。
app.config(["$routeProvider",function($routeProvider){
$routeProvider
.when("/",{
templateUrl : 'views/home/login.html',
controller : 'homeCtrl'
})
.when("/dashboard",{
templateUrl : 'views/home/dashboard.html',
controller : 'dashboardCtrl',
authenticated : true
})
.otherwise('/',{
templateUrl : 'views/home/login.html',
controller : 'homeCtrl'
})
}]);
app.run(["$rootScope","$location","authFactory",function($rootScope,$location,authFactory){
$rootScope.$auth = authFactory;
$rootScope.$on('$routeChangeStart',function(event,next,current){
if(next.$$route.authenticated){
var userAuth = authFactory.getAccessToken();
if(!userAuth){
$location.path('/');
}
}
});
}]);
如果用户当前已登录,我想限制对登录页面的路由访问..
请帮帮我
答案 0 :(得分:1)
您可以单独处理这两个条件,如下所示。
var userAuth = authFactory.getAccessToken();
// Redirect to login if auth token is not available
if(next.$$route.authenticated && !userAuth) {
$location.path('/');
}
// Redirect to dashboard if valid auth token is available and user is in an unauthenticated page (login may be)
if(!next.$$route.authenticated && userAuth) {
$location.path('/dashboard');
}