基于用户角色的UI-Router 1.0重定向 [英] UI-Router 1.0 redirect based on a user role

查看:79
本文介绍了基于用户角色的UI-Router 1.0重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在升级到ui-router@1.0.0-beta.2,并尝试找出如果用户没有必要的权限将用户重定向到其他状态的最佳方法是什么.

I'm upgrading to ui-router@1.0.0-beta.2 and trying to figure out what is the best way to redirect user to a different state if he doesn't have necessary permissions.

这就是我所拥有的:

.state('company_dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard.html',
    controller: 'CompanyDashboardCtrl',
    resolve: {
        user: function(UserService) {
            return UserService.getActiveUser();
        },
        company: function(UserService) {
            return CompanyService.getActiveCompany();
        },
        permissions: function(CompanyService, user, company){
            return CompanyService.getUserPermissions(company, user);
        }
    },
    onEnter: function($state, permissions) {
        if (permissions.canAccessDashboard === false)
            return $state.go('company_landing_page');
    }
})

上面的示例有效,但是它记录了以下错误:TransitionRejection(type: 2, message: The transition has been superseded by a different transition, detail: Transition#1( ''{} -> 'company_landing_page'{} ))这让我认为应该有更好的方法.

The above example works, but it logs the following error: TransitionRejection(type: 2, message: The transition has been superseded by a different transition, detail: Transition#1( ''{} -> 'company_landing_page'{} )) which makes me think, there should be a better way.

旁边的问题,在resolve期间检查权限是一种好习惯吗?

Side question, is it the good practice to check permissions during the resolve?

更新:

$state.go()更改为$state.target()可以帮助我摆脱控制台错误. 此评论提供了帮助. 尽管问题仍然存在,但我是否在正确的位置进行操作?

Changing $state.go() to $state.target() helped me to get rid of the console error. This comment has helped. Though the question stands, whether I'm doing it it the right place?

推荐答案

我将数据属性添加到您的状态,如下所示:

I would add a data property to your state as follows:

.state('company_dashboard', {
    data: {
           requiresAuthentication: true
    }
}

然后:

app.run(function ($rootScope, $state) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
        // Check if user is authenticated
        // And route requires authentication
       if (!toState.data.requiresAuthentication) {
            $state.go(toState.name, toParams);
       } else if (user && toState.data.requiresAuthentication) {
            $state.go(toState.name, toParams);
       } else {
            $state.go('login');
       }
    });
});

即使我确定它可以做得更好,这似乎也可以很好地工作,但是我希望这可以使您对如何进行操作有所了解.

This seems to work quite well even if I am sure it can be more polished, but I hope this gives you an idea on how you may proceed.

这篇关于基于用户角色的UI-Router 1.0重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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