Home > Software engineering >  How can use Two roles in attribute role
How can use Two roles in attribute role

Time:10-24

I have a problem with the insertion of two roles in the directive [role] Code HTML

<app-authorize-veiw [role]="'Admin'">
  <ng-container Authorized>
<a [routerLink]="['/DemandeConges',row.id]">
  <button mat-icon-button  >
  <mat-icon color="secondary">visibility</mat-icon>
</button>
</a>
  </ng-container>
</app-authorize-veiw>

code html of app-authorize-view>

<ng-content *ngIf="!isAuthorized()" select ="[notAuthorized]"></ng-content>
<ng-content *ngIf="isAuthorized()" select ="[Authorized]"></ng-content>

Ts file

export class AuthorizeVeiwComponent implements OnInit {

  constructor(private securityService:SecurityService) { }

  ngOnInit(): void {
  }


 @Input()
  role: string='';
public isAuthorized(){

  if(this.role){
return this.securityService.getRole() === this.role;

  }else {
    return this.securityService.isAuthenticated();
  }

please someone help me

CodePudding user response:

In order to accept more than one roles, you will need to update your code. These changes include:

  1. @Input row input.
  2. isAuthorized() function.

First, you will need to update your input to accept array of string instead of a string.

Then in the isAuthorized function, you need to loop through the requiredRoles to check if the currentRole from the securityService's role matches any of the supplied requiredRoles.

authorizeView.component.ts

export class AuthorizeViewComponent {

  ...

  // update to array string to accept more than one roles.
  @Input()
  public requiredRoles: string[] = []; 

  constructor(private securityService: SecurityService) { }

  public isAuthorized(){

    if(this.requiredRoles.length === 0)
      return this.securityService.isAuthenticated();

    const currentRole = this.securityService.getRole();

    // currentRole has to match at least one of the required roles to be true.
    const hasRequiredRole = this.requiredRoles
      .some(role => currentRole === role);

    return hasRequiredRole;
  }

  ...

}

example.component.html

...

<app-authorize-veiw [requiredRoles]="myRoles">
  <ng-container Authorized>
    <h2> You are Authorized! </h2>
  </ng-container>
</app-authorize-veiw>

...

example.component.ts

export class ExampleComponent {

  ...

  public myRoles = ['Admin', 'Student'];

  ...
}
  • Related