Angular 2 roles and permissions

我们两清 提交于 2019-12-04 09:33:47

You should store the permissions in the service itself instead of in the guard.

So when the use authenticates, you store the permission in a property of the Authentication Service. Then in the guard, you call the this.authService.<property> to use the permission. In any other component, you can do the same, this.authService.<property> to get the user's permission level

Since the service will be passed around as a singleton, all components will have access to the same property.

Based on the @Dave V response, you can implement your own "can" service which makes a little the code more readable. For example:

@Injectable()
export class UserCan {

  constructor (private _auth: AuthService)
  {

  }

  public canDoWhatever()
  {
    return (this._auth.roles.indexOf("Whatever") > -1);
  }

}

And in your Component s you can inject it:

export class YourComponent {
  private canDoWhatever: boolean;

  constructor(private _userCan: UserCan) {
    this.canDoWhatever = _userCan.canDoWhatever();
  }

}

And finally in your html:

<div *ngIf="canDoWhatever">

For somebody who is looking for the library, you can check out ngx-permissions. It will remove an element from DOM, lazy module compatible, isolated module compatible, else then syntax is supported.

Add library

  @NgModule({

  imports: [
    BrowserModule,
     NgxPermissionsModule.forRoot()
  ],

})
export class AppModule { }

Load permissions

constructor(private permissionsService: NgxPermissionsService,
       private http: HttpClient) {}

ngOnInit(): void {
    const perm = ["ADMIN", "EDITOR"];

    this.permissionsService.loadPermissions(perm);

     this.http.get('url').subscribe((permissions) => {
       //const perm = ["ADMIN", "EDITOR"]; example of permissions
       this.permissionsService.loadPermissions(permissions);
    })
  }

Use in templates

<div *ngxPermissionsOnly="['ADMIN', 'GUEST']">
    <div>You can see this text congrats</div>
</div>

For better documentation, visit wiki page.

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