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?