ui-router: default route based on user role

倾然丶 夕夏残阳落幕 提交于 2020-01-01 03:17:07

问题


I'm using UI router in my project. The home page of my application consists of 4 tabs, each routing to a different template. This is my current routing code, im using a forEach to create 6 routes.

['Draft','Assigned','InProgress','Completed','Rejected','All'].forEach(function (val) {
        $stateProvider.state({
            name: 'root.jobs.list.' + val.toLowerCase(),
            url: '/' + val.toLowerCase(),
            views: {
                'currentTab': {
                    templateUrl: 'adminworkspace/jobs',
                    controller: 'JobsController'
                }
            },
            data: {
                userJobsStatus: val
            }
        });
    });

By default when the user logs in, it goes to "root.jobs.list.draft". How do redirect to a given state based on the logged in user's role (Admin, User, Clerk etc..). If want to redirect all users that are part of the "Engineer" or "Lead Engineer" role to "root.jobs.list.inprogress"

I originally had this in the controller, but as you can see, it didn't work, because each time I clicked on a tab, it always routes back to "root.jobs.list.inprogress"

    if (user !== undefined) {
        if (user.BusinessRole == "Engineer" || user.BusinessRole == "Lead Engineer")
            $state.go('root.jobs.list.inprogress');
    }

回答1:


I already have had to solve that :

I've registered a state that was used only to handle the default page based on the role.

        $urlRouterProvider.otherwise("/");
        $stateProvider.state("default", {
            url:"/",
            templateUrl: "app/core/home/default.html",
            controller: "DefaultController"
        });

The the controller was simply :

(function () {
    "use strict";

    angular.module("core").controller("DefaultController", [
        "$rootScope",
        "$state",
        "roles",
        function ($rootScope, $state, roles) {
            if ($rootScope.hasPermission(roles.SomeRoleName)) {
                $state.go("someStateName");
            } else if ($rootScope.hasPermission(roles.SomeRoleName)) {
                $state.go("someStateName");
            }
        }
    ]);
})();



回答2:


If the link of the default state is same for each role e.g /user/home for both admin and user. One thing we can do is to show different html templates in the default state of the app based on roles. ui-router provides @stateProvider service which has properties templateProvider and ControllerProvider properties. We can use them to figure out which template and controller we want to use for same default state. Here is the documentation link.



来源:https://stackoverflow.com/questions/37003470/ui-router-default-route-based-on-user-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!