避免在AngularJS中直接访问URL

Avoid direct URL access in AngularJS

本文关键字:访问 URL AngularJS      更新时间:2023-09-26

我有一个使用ui-router路由的web应用程序。有一个用户管理模块,其中有特定的角色给用户(角色x, y和z)。当角色x的用户登录时,他将被限制在ui-router的某些状态,例如:"仪表板"。

当用户登录时,我已经将用户的角色保存在cookie变量中(使用$cookie)。当角色x的用户像这样登录时,我还使用ng-hide隐藏仪表板导航侧边栏:

HTML:

<li ui-sref-active="active">
   <a ui-sref="dashboard" ng-hide="roleIsX()">
       <i class="fa fa-laptop"></i> <span class="nav-label">Dashboard</span>
   </a>
</li>

控制器:

$scope.roleIsX = function() {
  if ($cookies.get('loggedInUserRole') === "x")
    return true;
  else
    return false;
}

这工作正常,但问题是,当任何用户登录时,他能够直接导航到一个URL写在地址栏。考虑到我的情况,有没有简单的方法可以解决这个问题?

我最终按照@Shivi的建议使用了resolveui-router。如果有人还在查找,下面是代码:

    app.config(['$urlRouterProvider', '$stateProvider', '$locationProvider',
        function($urlRouterProvider, $stateProvider, $locationProvider){
         ...
        .state('user-management', {
          ...
          ...
          resolve: { 
            roleAuthenticate: function($q, UserService, $state, $timeout) {
              if (UserService.roleIsX()) {
                // Resolve the promise successfully
                return $q.when()
              } else {
                $timeout(function() {
                  // This code runs after the authentication promise has been rejected.
                  // Go to the dashboard page
                  $state.go('dashboard')
                })
                // Reject the authentication promise to prevent the state from loading
                return $q.reject()
              }
            }

          }
        })

此代码检查roleIsX是否继续状态,否则打开dashboard状态。

有用的参考:angular ui-router登录认证-答案由@MK Safi

监听$locationChangeStart事件,并在需要时阻止它:

$scope.$on("$locationChangeStart", function(event, next, current) {
    if (!$scope.roleIsX()) {
        event.preventDefault();
    }
});