当涉及到只有登录用户才能查看的页面时,我在该页面的 Controller 中有一个这样的功能;
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 现在在配置 block 中具有 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');
}
});
就是这样。您所要做的就是将该逻辑放在配置 block 中,因为它应该检查每个状态更改...
关于javascript - Angular - protected 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34710143/