angularjs:app.config 中的条件路由 [英] angularjs: conditional routing in app.config

查看:23
本文介绍了angularjs:app.config 中的条件路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 angular.js ui-router 中遇到问题,无法解决.

I'm facing an issue in angular.js ui-router and not able to sort it out .

如果用户是 EnterpriseAdmin,我希望用户访问配置中定义的所有路由,如果用户是 Enterprise 用户,我希望用户访问一些路由.

I want user to access all routes defined in config if the user is EnterpriseAdmin and restrict some routes if the user is Enterprise user.

 var adocsModule = angular.module('myApp', ['ngResource', 'ngRoute','ui.bootstrap','ui.router', 'ngAnimate']) 
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
   $stateProvider.state('Registration', {
        url: "/Registration",
        templateUrl: '/Scripts/App/Registration/Templates/registration.html', controller: 'CoursesController'
    })
    .state('Registration.Instructors', {
         url: "/Instructors",
         templateUrl: '/Scripts/App/Instructors/Templates/instructors.html', controller: 'InstructorController'
    })
    .state('Registration.Courses', {
         url: "/Courses",
         templateUrl: '/Scripts/App/Instructors/Templates/courses.html', controller: 'CoursesController'
    })

谁能帮我解决这个问题,因为根据我的理解,app.js 在所有控制器之前加载.如果用户是 EnterpriseAdmin 或 Enterprise 用户,我当然可以检查控制器,但到那时所有路由都已配置并且用户可以访问它们.

Can someone help me solve this issue because as per my understanding app.js is loaded before all controllers . Surely I can check in the controller if the user is either EnterpriseAdmin or Enterprise user but up to that time all routes are already configured and the user has access to them.

有什么办法可以在配置块中进行ajax调用,然后定义一个全局变量,然后通过检查它我可以配置一些路由吗??

Is there any way that I can do ajax call in the config block and then define a global variable and then by checking it i can configure some routes or not ??

任何帮助将不胜感激问候

Any help will be appreciated Regards

推荐答案

$stateProvider.state 有一个 data 属性.一种方法是为您的状态添加身份验证选项.

$stateProvider.state has a data property. One way is to add auth option to your states.

$stateProvider.state('Registration.Instructors', {
     url: "/Instructors",
     templateUrl: '/Scripts/App/Instructors/Templates/instructors.html', 
     controller: 'InstructorController',
     data: { auth: "EnterpriseAdmin"}
})

然后您可以在任何状态开始加载之前侦听 ui-router 触发的事件,并在用户未经授权时阻止它:

then you can listen to event fired by ui-router before any state starts loading and prevent it if the user is unauthorized:

app.run(function($rootScope, user){
  $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
    if ( toState.data.auth === 'EnterpriseAdmin' && !user.isAdmin() ) {
        event.preventDefault();
        return false;
    }
  })
});

您甚至可以根据您的 ui 逻辑将他重定向到另一个状态:

You can even redirect him to another state, based on your ui logic:

 $state.go('login');

这篇关于angularjs:app.config 中的条件路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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