Angular UI Router 1.0.0 - 使用$ transitions.onBefore防止路由加载

Gro*_*ler 5 javascript state angularjs angular-ui-router

我升级到UI路由器1.0.0,它已从更改.$on($stateChangeX$transitions.onX((请参阅此处的$ transitions).

我需要在导航到页面之前解析用户的个人资料及其访问权限(例如,用户永远不应该看到他们尝试过渡到的页面).在此之前,我能够resolve直接使用a state并通过顺序传递我需要的东西,如下:

state('my-state', {
        ...
        resolve : {
            ProfileLoaded : ['$rootScope', function ($rootScope) {
                return $rootScope.loadProfile();
            }],
            access: ['Access', 'ProfileLoaded', function (Access, ProfileLoaded) {
                return Access.hasORRoles(['admin']); //either $q.reject(status code); or "200"
            }]
        }
    })
Run Code Online (Sandbox Code Playgroud)

然后我可以轻松地检索错误类型$stateChangeError:

app.run(...
    $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {

       if (error === 401) {
           $state.go('home');
       }
       ...
Run Code Online (Sandbox Code Playgroud)

$transitions,我正在尝试做同样的事情......

.state('user.my-page', {
  ...
  data: {
    loadProfile: true,
    roles: [
      'admin'
    ]
  }
});


app.run(...

  $transitions.onBefore({to: profile}, function(trans) {
    return loadProfile().then(function (prof) {
      var substate = trans.to();
      return Access.hasORRoles(substate.data.roles); //either $q.reject(status code); or "200"
    });
  });

  $transitions.onError({}, function(trans) {
    var error = trans && trans._error;

    if (error == 401) {
      $state.go('home');
    }
    ...
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:

是否onBefore做同样的事情,resolve在保证用户检查数据之前无法导航方面?页面仍在加载,然后$state.go在页面加载后重定向.

小智 1

只为那些仍然登陆这里的人。

您可以返回一个承诺以阻止网站加载。

$transitions.onBefore({}, function(transition) {
      return new Promise((resolve) => { 
      // Do auth.. 
      return Access.hasORRoles(['admin']);
   });
});
Run Code Online (Sandbox Code Playgroud)