Angular UI Router 1.0.0 - 使用$ transitions.onBefore防止路由加载 [英] Angular UI Router 1.0.0 - prevent route load with $transitions.onBefore

查看:263
本文介绍了Angular UI Router 1.0.0 - 使用$ transitions.onBefore防止路由加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我升级到UI路由器1.0.0,已从。$ on($ stateChangeX 更改为 $ transitions.onX(在此处查看$ transitions )。

I upgraded to UI Router 1.0.0, which has changed from .$on($stateChangeX to $transitions.onX( (see $transitions here).

我需要在导航到页面之前解析用户的个人资料及其访问权限(例如,用户永远不应该看到他们试图转换到的页面)。之前,我能够直接在中使用 resolve 并按顺序传递我需要的东西,如下:

I need to resolve the user's profile and their access BEFORE navigation to the page (e.g. the user should never see the page they're attempting to transition to). Before, I was able to use a resolve directly in the state and pass thru things I need sequentially, as such:

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"
            }]
        }
    })

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

Then I could easily retrieve the error type in $stateChangeError:

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

       if (error === 401) {
           $state.go('home');
       }
       ...






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


With $transitions, I'm trying to do the same thing...

.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');
    }
    ...

所以我的问题是:

onBefore 执行与 resolve 相同的操作,以确保用户在数据出现之前无法导航检查?页面仍在加载,然后在页面加载后用 $ state.go 重定向。

Does onBefore do the same thing as resolve in terms of ensuring the user can't navigate before data is checked? The page is still loading and THEN redirecting with $state.go after the page loads.

推荐答案

仅适用于仍在此登陆的人。

Just for people who are still landing here.

您可以返回一个promisse以防止该网站fr om loading。

You can return a promisse to prevent the site from loading.

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

这篇关于Angular UI Router 1.0.0 - 使用$ transitions.onBefore防止路由加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆