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

问题描述

我面临angular.js UI路由器的问题,而不是能够梳理出来。

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

我想用户访问配置定义的所有路线,如果用户是EnterpriseAdmin并限制部分航线如果用户是企业用户。

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或企业用户,但到那个时候已经配置的所有路线,并且用户对它们的访问。

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 ??

任何帮助将AP preciated
问候

Any help will be appreciatedRegards

推荐答案

$ stateProvider.state有一个数据属性。一种方法是身份验证选项添加到你的状态。

$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路由器发射事件的任何状态开始装载和prevent之前,如果用户未经授权:

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.transitionTo('login');

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

08-13 12:16