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

查看:33
本文介绍了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天全站免登陆