使用 angularJS + ui.router 在 `$stateChangeStart` 上重定向

And*_*des 1 redirect angularjs angular-ui-router

尝试将未经身份验证的用户重定向到登录屏幕。

我在用着ui.router 和指令来检查登录的用户。但它没有按我的预期工作。它在页面加载之前没有检查,并且我因连续重定向而卡在该页面上。

路由配置:

//User profile
    .state('UserProfile', {
        url: "/u/:id",
        data: {
            restrict: true,
            name: "Your Profile",
            header: true,
            footer: false,
            css: true,
            transparentHeader: true
        },
        templateUrl: "app/partials/user/userProfile.html",
        controller: "userProfileController"
    })

//Login page for not authenticated users
    .state('LoginPage', {
        url: "/login/",
        data: {
            restrict: false,
            name: "Login",
            header: false,
            footer: false,
            css: false,
            transparentHeader: false
        },
        templateUrl: "app/partials/common/loginPage.html",
        controller: "loginController"
    })
Run Code Online (Sandbox Code Playgroud)

服务:

.factory('userService', ['$cookies', function($cookies){

   var userData = {
        isLogged: false,
        userId: "",
        firstName: "",
        profilePic: ""
    };


    return userData;

}]);
Run Code Online (Sandbox Code Playgroud)

指示:

socialMarkt.directive('checkUser', ['$rootScope', '$state', 'userService', function ($r, $state, userService) {
    return {
      link: function (scope, elem, attrs, ctrl) {
        $r.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){
          event.preventDefault();
          if($state.current.data.restrict){
            if(!userService.isLogged){
              $state.go('LoginPage');
            }
          }
        });
      }
    }
  }]);
Run Code Online (Sandbox Code Playgroud)

我刚刚将其添加到一页进行测试。因此,如果用户未登录,据说它会使用 重定向到登录页面$state.go('LoginPage')

And*_*des 5

我更改了验证登录状态的方式。

我在 .run 上做的

.run(['$rootScope', '$state', 'userService', '$sessionStorage', function($rootScope, $state, userService, $sessionStorage){

  $rootScope.$on('$stateChangeStart'
    , function(event, toState, toParams, fromState, fromParams) {

    //Detecting sessions
    if($sessionStorage.userData){
        var goodORnot = $sessionStorage.userData.isLogged;
    }else{
        goodORnot = false;
    }

    var isAuthenticationRequired =  toState.data 
          && toState.data.requiresLogin 
          //&& !userService.isLogged
          && !goodORnot
      ;

    if(isAuthenticationRequired)
    {
      event.preventDefault();
      $state.go('LoginPage');
    }
  });
}]);
Run Code Online (Sandbox Code Playgroud)