检查用户是否在模板加载之前登录,根据用户登录执行 2 个不同的操作

check if user logged in before template loads, execute 2 different actions depending user is logged in

我正在学习 angular.js 和 ui-router。所以我想了解: 1. 如何根据用户是否登录在一种状态下执行两种不同的操作。 2. 在几个状态下如果用户未登录则重定向到主页

示例如下: 有一项服务 "Atuhentication" 可以计算经过身份验证的用户。但是我无法将它加载到 module.config() 它会引发错误。

$stateProvider
    .state('home', {
        // if user is logged in go to state "chat"
        // else go to state "welcome"
    })
    .state('chat', function(){
        // if user is not logged in redirect to home page
    })

我试图在状态的控制器中创建它,但这是一种肮脏的方式,因为它加载模板和控制器,然后检查用户是否登录,如果没有则重定向。

所以亲爱的朋友们,请指出正确的移动方向

您始终可以使用 $stateChangeStart 状态更改时正在广播的事件挂钩并防止状态更改。您可以在整个应用程序可用的任何顶级控制器中添加此事件侦听器(例如添加到 body 标签的控制器),或者您可以使用 $rootScope 在任何服务中添加此事件侦听器代码,例如以下:

var protectedStates = ['home', 'chat'];

$rootScope.$on('$stateChangeStart', function(event, toState, toParams) {
     // See if state being transitioned needs to be access checked
     if (protectedStates.indexOf(toState.name) > -1) {
         if (!userLoggedIn) {
              // Prevent the current state from being changed
              event.preventDefault();
              $state.go('home');       // go to home page or login page.
         }
     }
});

更多参考:http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$state

希望对您有所帮助!

谢谢,
SA