Angular ui-router:如何防止访问状态 [英] Angular ui-router: how to prevent access to a state

查看:25
本文介绍了Angular ui-router:如何防止访问状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello I'm new to angularJS and have been trying to prevent access to certain states based on user critera.

这个,来自 ui-router 的常见问题 准确地描述了我想要做什么,但我无法让它正常工作.除了数据对象之外,我还需要什么才能完成此操作?

This, from ui-router's FAQ describes exactly what I want to do, but I cant get it to work properly. What do I need to but in the data object exactly to accomplish this?

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

(I saw someone throwing in "true" on some blog post tutorial and using it like how I have, but that doesnt seem to work because I get an error that says needAdmin is not defined)

这是我的代码:

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');
    }

  });
}]);

推荐答案

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

If a state has no data, then to.data is undefined. Try this:

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

这篇关于Angular ui-router:如何防止访问状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆