简体   繁体   中英

Angular 8 - How to authorize permissions instead of roles with ngx-permissions?

I'm using ngx-permissions ( https://www.npmjs.com/package/ngx-permissions ) in a project so that I can manage users permissions on my application.

As far as I can see, we can authorize roles in html part but not permissions...

Here's what we want:

Html:

<div *ngxPermissionsOnly="['voirResources']">1232465</div>

Typescript:

  ngOnInit() {
    const roleMetier: Role = new Role();
    roleMetier.nom = 'ADMIN';
    roleMetier.permissions = ['voirHighlightCard', 'voirResources', 'voirTout', 'voirNextSteps'];
    this.rolesService.addRole(roleMetier.nom, roleMetier.permissions);

    this.permissionsService.loadPermissions(['ADMIN']);
  }

As you could see, I set my role Admin with some permissions. After that, I load admin permissions for my current users.

In Html code, I add *ngxPermissions="['voirResources']" so that only users with permission "voirResources" can see the div content.

Here's the code on stackblitz => https://stackblitz.com/edit/angular-poc-ngx-permissions

My questions are:

  • can we do it with ngx-permissions?
  • if we can't do it with ngx-permissions, do you know another npm packages that I can use? I don't want to develop another ACL package if there's something cool to use ^^

Thanks for your advice!

You need to use this.permissionsService.addPermission(['seeContent']); or via loadPermission

So modification to your stackblitz:

ngOnInit() {
// this.chargerPermissionsUtilisateur();

this.chargerRoleUtilisateur();
console.log(this.rolesService.getRoles());
}

chargerRoleUtilisateur() {
    const roleMetier: Role = new Role();
    roleMetier.nom = 'ADMIN';
    roleMetier.permissions = ['seeContent'];

    this.permissionsService.addPermission(['seeContent']);

    this.rolesService.addRole(roleMetier.nom, roleMetier.permissions);
}

Alternatively you can just change your chargerPermissionsUtilisateur() method to:

this.permissionsService.loadPermissions(['seeContent']);

and change the order of your ngOnInit

this.chargerPermissionsUtilisateur();
this.chargerRoleUtilisateur();

https://stackblitz.com/edit/angular-poc-ngx-permissions-qxi4mz

使用 8.1.1 版本可以在一行中完成

 this.rolesService.addRoleWithPermissions('ADMIN', ['seeContent']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM