Javascript 角度保护页面
当涉及到只有登录的用户才能查看的页面时,我在该页面的控制器中有这样一个功能Javascript 角度保护页面,javascript,angularjs,authentication,Javascript,Angularjs,Authentication,当涉及到只有登录的用户才能查看的页面时,我在该页面的控制器中有这样一个功能 if ( user is not logged in ) { $state.go('someState') } else { // prepare the page as normal } 考虑到我需要在每一个我想要认证的页面上写下类似的内容,我觉得可能有一个更优雅的解决方案 我应该在app.run中执行此操作吗?差不多 var protectedPages = a list of prot
if ( user is not logged in ) {
$state.go('someState')
} else {
// prepare the page as normal
}
考虑到我需要在每一个我想要认证的页面上写下类似的内容,我觉得可能有一个更优雅的解决方案
我应该在app.run中执行此操作吗?差不多
var protectedPages = a list of protected pages
if ( protectedPages && user is not logged in ) {
$state.go('someState')
} else {
// prepare the page as normal
}
还是有一种完全不同的更标准的方法呢?一般,我相信对于这种情况最好的方法是设置一个页面更改事件,并在那里定义逻辑 但是为了定义逻辑,您需要知道下一个状态的一些属性,以便可以为每个状态添加一些数据,如requiresLogin。这些属性是完全自定义的,因此您可以定义任何需要的内容 让我们定义一些状态,requiresLogin
$stateProvider
.state('exampleState', {
url: '/example',
controller: 'ExampleController as vm',
templateUrl: 'example.html',
data: {
requiresLogin: true,
someOtherCustomProperty: 'It can be anything'
}
})
正如您所看到的,exampleState现在在配置块中具有requiresLogin属性,我们可以获取此数据,并允许用户转到exampleState或将其重定向到其他状态
$rootScope.$on('$stateChangeStart', function (event, toState) {
// if next state requires login and user is not loged in
if (toState.data.requiresLogin && userNotLogedIn) {
// prevent default behaviour and implement your logic here
event.preventDefault();
// TODO
// as an example you can redirect user to login state
$state.go('login');
}
});
就这样。您所要做的就是将该逻辑放入配置块中,因为它应该检查每个状态更改…而不是白名单,如果每个页面都能向检查者报告登录的需要,那就太好了。这看起来很好,明天会给它一个机会,让您知道它是如何进行的!一种简单的方法是将所有受保护的页面保持在相同的父级状态…然后对该父级使用解析