Taxyy
Taxyy

Reputation: 33

Check role claims and show elements if true

I am writting an app with angular on front + asp.net on backend. I have 2 roles: user and admin. There are a few buttons on my navbar that I want to hide from user role. My function for checking if currently logged user role is admin:

public isUserAdmin = (): boolean => {
    var token = localStorage.getItem("token");
    const decodedToken = this._jwtHelper.decodeToken(token!);
    const role = decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
    return role === 'Admin';
  } 

Above code is tested and it works, currently I am using it for guard.

My navbar html:

     <li class="nav-item">
        <a class="nav-link" *ngIf="isUserAdmin" routerLink="manufacturers">Manufacturers</a>
      </li>

navbar.ts:

export class HeaderComponent implements OnInit {
  public isUserAdmin: boolean = false;
  ...
  constructor(private userService: UserService, private _router: Router) {
    this.userService.adminChanged
      .subscribe(res => this.isUserAdmin = res); 
  }

To get above navbar.ts code work I modified userService:

export class UserService {

  private _adminChangeSub = new ReplaySubject<boolean>(1);
  public adminChanged = this._adminChangeSub.asObservable();

  constructor(private _http: HttpClient, private _envUrl: EnvironmentUrlService, private _jwtHelper: JwtHelperService) { 
  }

  public isUserAdmin = (): boolean => {
    var token = localStorage.getItem("token");
    const decodedToken = this._jwtHelper.decodeToken(token!);
    const role = decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
    this._adminChangeSub.next(true);
    return role === 'Admin';
  } 

But it just doesn't work. Element in navbar is still here even If i log into admin account. Also when I try to console.log(this.isUserAdmin) in constructor right after subscribing it return false. How can I hide buttons from navbar when user is not an admin?

Upvotes: 0

Views: 530

Answers (1)

Jeremy Thille
Jeremy Thille

Reputation: 26370

No need for observables, subscriptions all all this arsenal. Simply use this :

<li class="nav-item">
    <a class="nav-link" *ngIf="userService.isUserAdmin" routerLink="manufacturers">Manufacturers</a>
</li>

And make it a getter in the service :

get isUserAdmin(): boolean => {
    var token = localStorage.getItem("token");
    const decodedToken = this._jwtHelper?.decodeToken(token!) || {};
    const role = decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
    return role === 'Admin';
} 

Upvotes: 1

Related Questions