Angular ui路由器:如何阻止访问一个状态

Angular ui-router: how to prevent access to a state

本文关键字:一个 状态 访问 路由器 ui 何阻止 Angular      更新时间:2023-11-11

你好,我是angularJS的新手,一直在尝试根据用户标准阻止访问某些状态。

这篇来自ui路由器常见问题解答的文章准确地描述了我想做什么,但我无法让它正常工作。除了在数据对象中,我还需要什么来实现这一点?

(我看到有人在一些博客文章教程中输入"true",并像我一样使用它,但这似乎不起作用,因为我收到一个错误,说needAdmin没有定义)

这是我的代码:

angular.module('courses').config(['$stateProvider',
    function($stateProvider) {
        // Courses state routing
        $stateProvider.
        state('listCourses', {
            url: '/courses',
            templateUrl: 'modules/courses/views/list-courses.client.view.html'
        }).
        state('createCourse', {
            url: '/courses/create',
            templateUrl: 'modules/courses/views/create-course.client.view.html',
            data: {
                needAdmin: true
            }
        }).
        state('viewCourse', {
            url: '/courses/:courseId',
            templateUrl: 'modules/courses/views/view-course.client.view.html'
        }).
        state('editCourse', {
            url: '/courses/:courseId/edit',
            templateUrl: 'modules/courses/views/edit-course.client.view.html',
            data: {
                needAdmin: true
            }
        });     
    }
]);

angular.module('courses').run(['$rootScope', '$state', 'Authentication', function($rootScope, $state, Authentication) {
  $rootScope.$on('$stateChangeStart', function(e, to) {
    var auth = Authentication;
    console.log(auth.user.roles[0]);
    if (to.data.needAdmin && auth.user.roles[0] !== 'admin') {
      e.preventDefault();
      $state.go('/courses');
    }
  });
}]);

我发现的最好的方法是使用解析:

    $stateProvider.        
    state('createCourse', {
        url: '/courses/create',
        templateUrl: 'modules/courses/views/create-course.client.view.html',
        resolve: {
           security: ['$q', function($q){
               if(/*user is not admin*/){
                  return $q.reject("Not Authorized");
               }
           }]
        }
    });

这将触发一个错误,如果不允许用户访问此状态,则会阻止用户访问。

如果您需要显示错误,或将用户发送到不同的状态,请处理$stateChangeError事件:

$rootScope.$on('$stateChangeError', function(e, toState, toParams, fromState, fromParams, error){
    if(error === "Not Authorized"){
        $state.go("notAuthorizedPage");
    }

如果您想检查所有状态的管理员访问权限,可以使用decorator将解析添加到所有状态。类似这样的东西:

$stateProvider.decorator('data', function(state, parent){
    var stateData = parent(state);
    var data = stateData.data || {};
    state.resolve = state.resolve || {};
    if(data.needAdmin){
       state.resolve.security = ['$q', function($q){
               if(/*user is not admin*/){
                  return $q.reject("Not Authorized");
               }
           }];
    return stateData;
});

我为当前的应用程序实现了类似的功能。如果用户未登录,我们将用户转发到登录表单。如果非管理员用户试图进入任何管理员状态,我们将转发到错误页面。

如果一个状态没有data,则to.data未定义。试试这个:

if (to.data && to.data.needAdmin && auth.user.roles[0] !== 'admin') {