angularjs: conditional routing in app.config

后端 未结 1 1309
旧巷少年郎
旧巷少年郎 2021-02-04 14:16

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

Issue:

I want user to access all routes defined in config if the user is EnterpriseA

相关标签:
1条回答
  • 2021-02-04 14:42

    $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"}
    })
    

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

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

     $state.go('login');
    
    0 讨论(0)
提交回复
热议问题