在Angular 4中使用权限的最佳方法是什么? [英] What's the best way to work with permissions in Angular 4?

查看:137
本文介绍了在Angular 4中使用权限的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 4项目中,我想使用从API获得的权限.权限另存为具有ID的数组.诸如用户或博客帖子之类的某些单个元素具有具有允许的权限的属性,该属性允许或不允许诸如id的数组之类的编辑或删除操作.

In my Angular 4 project I would like to work with permissions, which I get from an API. Permissions are saved as array with ids. Some single elements like user or blog post have property with allowed permissions, which allow or not allow actions like edit or delete, as array with ids.

在Angular 4项目中检查和处理权限的最佳方法是什么? Angular是否有一些权限管理之外的解决方案?如果Angular没有现成的解决方案,有人可以给我一些实现权限处理的想法吗?

What's the best way to check and to handle permissions in Angular 4 projects? Has Angular some out of the bos solutions for permissions handling? Can somebody give me ideas for realization of permissions handling, if Angular doesn't have some out of the box solution?

推荐答案

像拉胡尔(Rahul)的评论说,开箱即用的一种解决方案更可能是您想要的Guard ..

like Rahul comment says the one solution out of the box is more likely what you want are Guard ..

记住防护仅用于路由..所以仅检查用户是否可以访问路由..但不能根据角色或其他内容显示组件中的单个元素,为此我建议您使用*ngIf或显示以渲染/显示或不显示某些UI元素...

Remember guard are only for ROUTING .. so only to check if a user can access a route or not .. but not to display single element in a component based on roles or whatever .. for that i suggest to you to use *ngIf or show to render/display or not some UI elements ...

对于基于角色的一名Guard(不仅使用auth还是不使用auth ..),您都可以执行以下操作:

For one Guard based on Roles (not only if use is auth or not) ..you can do something like:

import { Injectable } from "@angular/core";
import { AuthService, CurrentUserService } from "app/shared/services";
import { Router, RouterStateSnapshot, ActivatedRouteSnapshot, CanActivate } from "@angular/router";
import { AspNetUsersDTO } from "app/shared/models";
import { Observable } from "rxjs/Rx";

@Injectable()
export class RoleGuard implements CanActivate {

    constructor(private authService: AuthService,
        private _currentUser: CurrentUserService,
        private router: Router) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return new Promise<boolean>((resolve, reject) => {

            if (!this.authService.isLoggedIn()) {
                resolve(false);
                return;
            }


            var currentUser: AspNetUsersDTO = new AspNetUsersDTO();

            this._currentUser.GetCurrentUser().then((resp) => {
                currentUser = resp;
                let userRole = currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0].toUpperCase() : '';
                let roles = route && route.data["roles"] && route.data["roles"].length > 0 ? route.data["roles"].map(xx => xx.toUpperCase()) : null;

                if (roles == null || roles.indexOf(userRole) != -1) resolve(true);
                else {
                    resolve(false);
                    this.router.navigate(['login']);
                }

            }).catch((err) => {
                reject(err);
                this.router.navigate(['login']);
            });
        });

    }

    canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {

        return new Promise<boolean>((resolve, reject) => {

            if (!this.authService.isLoggedIn()) {
                resolve(false);
                return;
            }


            var currentUser: AspNetUsersDTO = new AspNetUsersDTO();

            this._currentUser.GetCurrentUser().then((resp) => {
                currentUser = resp;
                let userRole = currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0].toUpperCase() : '';
                let roles = route && route.data["roles"] && route.data["roles"].length > 0 ? route.data["roles"].map(xx => xx.toUpperCase()) : null;

                if (roles == null || roles.indexOf(userRole) != -1) resolve(true);
                else {
                    resolve(false);
                    this.router.navigate(['login']);
                }

            }).catch((err) => {
                reject(err);
                this.router.navigate(['login']);
            });
        });

    }
}

然后您就可以像这样在路由中使用

And then you can use in your routing like:

{
        path: 'awards-team',
        component: AwardsTeamComponent,
        canActivateChild: [RoleGuard],
        children: [
          {
            path: 'admin',

            component: TeamComponentsAdminComponent,
            data: { roles: ['super-admin', 'admin', 'utente'] }
          },
          {
            path: 'user',

            component: TeamComponentsUserComponent,
            data: { roles: ['utente'] }
          }
        ]
      }

这篇关于在Angular 4中使用权限的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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