@ngx-security/roles
v18.0.0
Published
Angular Security Roles Module
Downloads
190
Maintainers
Readme
ngx-security/roles
Installation
npm install --save @ngx-security/core @ngx-security/roles
Setup
Import SecurityCoreModule
and SecurityRolesModule
in app module.
@NgModule({
imports: [
BrowserModule,
SecurityCoreModule.forRoot(),
SecurityRolesModule.forRoot()
],
bootstrap: [AppComponent]
})
export class AppModule {
}
Now you are ready to use it. See SecurityCoreModule for SubjectService
implementation which provide authorities as roles.
Usage
Structural directives
<p *hasRole="'ROLE_1'">This should see users with ROLE_1</p>
<p *hasAnyRole="['ROLE_1','ROLE_2']">This should see users with ROLE_1 or ROLE_2</p>
<p *hasRoles="['ROLE_1','ROLE_2']">This should see users with ROLE_1 and ROLE_2</p>
Pipes
<p *ngIf="'ROLE_1' | hasRole">This should see users with ROLE_1</p>
<p *ngIf="['ROLE_1','ROLE_2'] | hasAnyRole">This should see users with ROLE_1 or ROLE_2</p>
<p *ngIf="['ROLE_1','ROLE_2'] | hasRoles">This should see users with ROLE_1 and ROLE_2</p>
Pipes with poetry
<p *ngIf="'user' | hasRole:'ROLE_1'">This should see users with ROLE_1</p>`
<p *ngIf="'user' | hasAnyRole:['ROLE_1','ROLE_2']">This should see users with ROLE_1 or ROLE_2</p>`
<p *ngIf="'user' | hasRoles:['ROLE_1','ROLE_2']">This should see users with ROLE_1 and ROLE_2</p>`
Advance setup
Implement custom custom SubjectRolesProvider
class:
import { Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { SubjectRolesProvider } from '@ngx-security/roles';
@Injectable()
export class MyRolesProvider extends SubjectRolesProvider implements OnDestroy {
private roles: BehaviorSubject<string[]> = new BehaviorSubject(['ROLE_1', 'ROLE_2']);
roles$: Observable<string[]> = this.roles.asObservable();
constructor() {
super();
}
ngOnDestroy(): void {
this.roles.complete();
}
getRoles(): string[] {
return this.roles.getValue();
}
}
Import SecurityRolesModule
in app module and set your custom SubjectRolesProvider
.
@NgModule({
imports: [
BrowserModule,
SecurityCoreModule.forRoot(),
SecurityRolesModule.forRoot({
subjectRoles: { provide: SubjectRolesProvider, useClass: MyRolesProvider }
})
],
bootstrap: [AppComponent]
})
export class AppModule {
}