在 angular.js 中,我在所有需要身份验证的 Controller 上执行以下操作:
function controller($state, $rootScope, $scope, oAuthService) {
//oAuthService is a custom service
if(!oAuthService.isAuthorized()) {
$state.go('401');
}
...
}
问题有两方面。首先,我不喜欢我必须将这 3 行复制并粘贴到每个需要身份验证的 Controller 的顶部。其次,如果您转换到另一个 Controller ,则不会检查身份验证(仅在页面硬刷新时检查)。这样做的最佳方法是什么?
最佳答案
在您的根 Controller 中添加以下代码行..
$rootScope.$on("$stateChangeStart", function (event, oAuthService) {
if(!oAuthService.isAuthorized()) {
$state.go('401');
event.preventDefault();
}
}
编辑
回答您的评论。
您应该在每个状态上设置一些 bool 属性,指示是否需要身份验证。
.state('home', {
url: '/home',
templateUrl: 'partial-home.html',
isSecured: true
})
然后
$rootScope.$on("$stateChangeStart", function (event, toState) {
if(!oAuthService.isAuthorized() && toState.isSecured && toState.name != '401') {
$state.go('401');
event.preventDefault();
}
}
关于javascript - Angular.js,如何检查 Controller 中的身份验证服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25189352/