如何在使用 angular 权限库定义权限时执行异步任务

How to do asynchronous task while defining a permission using angular permission library

我正在使用 angular-permission library along with ui-router and satellizer

以下是 home 的状态定义。因为我正在使用 angular-permission.

检查用户是否获得授权
$stateProvider.state('500', home);
var home = {
  abstract: true,
  url: '/home',
  data: {
    permissions: {
      only: ['loggedin',],
      redirectTo: {
        loggedin: 'login',
      },
    }
  },
  templateUrl: 'components/home/home.view.html',
  controller: 'HomeCtrl as home'
};

以下是loggedin

的权限定义
PermPermissionStore.definePermission('loggedin', isAuthenticated);

function isAuthenticated(permissionName, transitionProperties) {
  // check if token is valid.
  if ($auth.isAuthenticated()) {
    return true;
  }
  // if not then refresh token
  return tokenRestService.refresh().then(
    function (response) {
      if (response != null) {
        $auth.setToken(response);
      }
    },
    function (response) {
      localStorage.removeItem('user');
    }
  );
}

但是当我进行异步调用时它有些不起作用。如果我按如下方式更改 isAuthenticated 函数,那么它可以正常工作,但如果令牌过期,我需要刷新令牌,否则,将用户重定向到登录页面。

function isAuthenticated(permissionName, transitionProperties) {
  if ($auth.isAuthenticated()) {
    return true;
  }
  return false;
}

来自 angular 的 doc-权限:

Sometimes you will need to call some a back-end api or do some other asynchronous task to check if permission is still valid. For that you can use promises and simply return them from validation function:

PermPermissionStore
  // Define user permission calling back-end
  .definePermission('hasValidSession', /*@ngInject*/function (Session) {
    // Let's assume that Session service calls backend API via $http and return promise:
    // -- $q.resolve() means that session is active 
    // -- $q.reject() means that session expired
    return Session.checkSession();
  });

但是当我在 definePermission 中使用服务时,它直接通过而没有任何重定向。

遵循文档:

 -- $q.resolve() means that session is active 
 -- $q.reject() means that session expired

Return 解决或拒绝了对 .then 方法的承诺:

PermPermissionStore.definePermission('loggedin', isAuthenticated);

function isAuthenticated(permissionName, transitionProperties) {
  // check if token is valid.
  if ($auth.isAuthenticated()) {
    return true;
  }
  // if not then refresh token
  return tokenRestService.refresh().then(
    function (response) {
      if (response != null) {
        $auth.setToken(response);
      }
      return $q.resolve();
    },
    function (response) {
      localStorage.removeItem('user');
      return $q.reject();
    }
  );
}