基于角色的AngularJS路由

基于角色的AngularJS路由

本文介绍了基于角色的AngularJS路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建基于角色的身份验证,并显示用户角色的可用内容.我的route.js

I am trying to create role based authentication and show an available content for user role. I have the following code in my route.js

Application.config(function($routeProvider, $locationProvider) {
    var role = ... ???
    if(role === 'ADMIN') {
        $routeProvider
            .when('/dashboard', {
                templateUrl: "views/adminDashboard.html",
                controller: "adminDashboardController"
            });
    }
    if(role === 'USER') {
        $routeProvider
            .when('/dashboard', {
                templateUrl: "views/userDashboard.html",
                controller: "userDashboardController"
            });
    }
});

如何获得用户角色?我有一个enpoint /user/me,它返回当前用户的角色,但是我不能在这里做http.

How can I get role for user? I have an enpoint /user/me which returns current user's role but I can't do http here.

推荐答案

$http服务不能注入到配置块的构造函数中,但是可以注入到路由的解析器函数中:

The $http service can not be injected into the construction function of config blocks, but it can be injected in resolver functions of routes:

Application.config(function($routeProvider, $locationProvider) {
    $routeProvider
        .when('/dashboard', {
            template: `
                <div ng-if="$resolve.role=='ADMIN'"
                     ng-include="views/adminDashboard.html">
                </div>
                <div ng-if="$resolve.role=='USER'"
                     ng-include="views/userDashboard.html">
                </div>
            `,
            controller: "dashboardController",
            resolve: {
                role: function($http) {
                    return $http.get("/user/me").then(function(response) {
                        return response.data;
                    });
                }
            }
        })
});

有关更多信息,请参见 AngularJS $ routeProvider API参考-.when方法.

For more information, see AngularJS $routeProvider API Reference - .when Method.

这篇关于基于角色的AngularJS路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 00:47