2016-04-14 23 views
1

当使用ui-router时,有什么方法可以根据cookie中的数据将用户重定向到特定状态?

我试图从.config()做到这一点,但因为我无法注入其他依赖关系,所以它不工作。

我也试过在.run()块上做,但它只是给出了一个循环(当然)。

这是我第一次尝试在.config()

function ConfigRouter($locationProvider, $stateProvider, $urlRouterProvider, Constant, localStorageService) { 
    $locationProvider.html5Mode(true); 

    $urlRouterProvider.when('/', function($injector) { 
     var $state = $injector.get('$state'); 
     checkState($state); 
    }); 
    $urlRouterProvider.when('', function($injector) { 
     var $state = $injector.get('$state'); 
     checkState($state); 
    }); 
    $urlRouterProvider.otherwise(function($injector) { 
     var $state = $injector.get('$state'); 
     $state.go('error'); 
    }); 

    function checkState($state) { 
     var userCookie = localStorageService.cookie.get(Constant.cookieName); 
     if(userCookie.type == 1) { 
      $state.go('home-app'); 
     } else if (userCookie.type == 2) { 
      $state.go('home-client'); 
     } //and so on 
    } 

} 

有没有办法做到这一点?或以其他方式实现相同的结果?基本上我需要根据用户角色将用户发送到应用程序的不同部分。如果他是一个管理员,客户端,主持人等。每个人都有一个特定的应用程序,并需要从服务器检索特定的数据,这就是为什么我想这样做,所以我可以请求数据上的每个州的决心。

回答

1

如果您正在使用的角度UI路由器,您可以使用resolve顶部状态下,你可以注入的服务,帮助你在

.run(["$rootScope", "$location", "$state", "services.userService", function ($rootScope, $location, $state) { 
     $rootScope.$on('$stateChangeStart', function (e, toState, toParams 
      , fromState, fromParams) { 
// validation 
}); 
验证cookie的

你也可以拦截并做到这一点

更多信息https://github.com/angular-ui/ui-router/wiki#resolve

和这里的例子 angular ui-router login authentication

Defer Angular UI Router $stateChangeStart until server authorization response receieved

EJ:

.state('main', { 
        templateUrl: 'app/modules/home/view.html', 
        abstract: true, 
        resolve: { 
         authorize: ['userService', "$state", "$q", 
          function (userService, $state, $q) { 
           return checkAuthorization(userService, $state, $q) 
            .then(function (user) { 
             return {user: user} 
            }); 
          }] 
        }, 
        controller: 'RootController' 
       }) 
// more states 

var checkAuthorization = function(userService, $state){ 
    //do all the necessary checks and return the user if he is already logged in 
//redirecct to other page if the check failed 
} 
0

我做的。运行部分用户检查:

.run(['$rootScope', '$state', '$cookies', 
    function ($rootScope, $state, $cookies) { 
     if ($cookies.get('token')) 
      $state.go('main'); 
     else 
      $state.go('guest) 
    }]); 

当然应该比你在饼干安装 '令牌' 中。而现在你不需要$ configRouterProvider .config