我是 AngularJS 的新手并创建了我的第一个单页应用程序。我创建了各种路由,其中一个用于主页 (/),另一个用于登录 (/login)。
当我的应用程序模块运行时,它首先初始化 $rootScope.authentication = false;并验证用户是否已登录,如果没有,则将用户重定向到/login 页面,否则为主页。
var myApp = angular.module('myApp', ['ngRoute']);
myApp.run(function($rootScope, $http, $location, $routeParams){
$rootScope.authenticated = false;
$rootScope.$on("$routeChangeStart", function(e, current, previous){
$http.get('api/user/authenticated')
.then(function(res){
if(res.data.authenticated == true && angular.isDefined(res.data.authenticated)) {
$rootScope.authenticated = res.data.authenticated;
$rootScope.clinicname = res.data.clinic_name;
$rootScope.email = res.data.email;
if(angular.isDefined(previous)) {
if (angular.isObject(current.$$route) && angular.isObject(previous.$$route)) {
if (current.$$route.originalPath === '/login') {
$location.path(previous.$$route.originalPath);
}
}
}
}
else {
$rootScope.authenticated = false;
if (angular.isObject(current.$$route)) {
if (current.$$route.originalPath !== '/login') {
$location.path('/login');
}
}
}
});
});
console.log($rootScope);
});
index.html
<body class="hold-transition skin-blue sidebar-mini">
<div ng-if="authenticated == false">
<section class="content-header">
<div ng-view></div>
</section>
</div>
<div ng-if="authenticated" class="wrapper">
<!-- Content here !-->
<div class="content-wrapper">
<section class="content-header">
<div ng-view></div>
</section>
</div>
</div>
现在的问题是,在用户未登录的情况下,先浏览首页,然后快速跳转到登录页面。
我想以某种方式处理这部电影。我做错了什么?
最佳答案
您想要的是在路由的 onEnter 回调中执行身份验证逻辑。
此事件将在继续执行之前完全解决,这意味着如果身份验证(或您需要执行的任何其他逻辑)失败,用户可以被重定向并且永远不会看到他们试图访问的路由。
.state("homepage", {
url: "/",
controller: 'homepageController',
templateUrl: "/homepage.html",
onEnter: ['$state', 'authService', function ($state, authService) {
if (!authService.hasPermission(this.name)) {
$state.go('login');
}
}]
})
在这个例子中,我使用了一个服务来检查用户是否被授权访问这个路由,但是你可以在这里执行你需要的任何逻辑。
关于javascript - 如何避免 AngularJS 页面抖动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36012210/