Hiding the required menu items for the particular user in angular 2

Heena picture Heena · Aug 4, 2018 · Viewed 8.2k times · Source

I have created an angular application in which I have a login form where i have implemented authentication using service and guard .

I have defined a interface user with username and password.Using this interface in authentication.service.ts I have defined two users admin and user.

I have also implemented a guard named authentication.guard.ts where I have taken CanActivate RouteGaurd to route the user to the page which he can access.

In my application there is an admin page which can only be accessed by admin user, so if the admin logs in only then it navigates to Admin Page .If user logs in then he will be redirected to Home Page skipping the Admin Page

When a admin or user logs into the application, a menu bar appears where I have three menu items Home, AdminActivity ,RegisterUser .

I am trying to hide the AdminActivity menu item if admin logs into the application and hide the RegisterUser menu item if user logs into the application.

I tried to import the authentication service in app.component.ts but I am unable to fetch the logged username and password.

Can anybody please help me out in implementing the desired functionality as I needed to implement in my application

Please access my sample application here

Answer

Abdul Rafay picture Abdul Rafay · Aug 4, 2018

Updated your sample code HERE

Used a BehaviorSubject for tracking user type and used it to show/hide menu items. You can use it for communicating within different components throughout the app. I removed some of your code which was causing errors in Stackblitz but don't focus on that.

Changes in AuthenticationService:

declared userType BehaviorSubject as:

  userType: BehaviorSubject<string> = new BehaviorSubject<string>(this.getUserType());

added method to get user type from local storage as:

  getUserType() {
    return localStorage.getItem('user')
  }

updating userType BehaviorSubject in login:

login(username, password) {
...
localStorage.setItem("user", this.user.username);
this.userType.next(this.user.username);

Changes in app.componet.ts:

subscribing to userType BehaviorSubject:

  userType: string = '';

  ngOnInit(){
    ...
    this.authService.userType.subscribe(value => this.userType = value);
  }

Changes in app.componet.html:

show/hide menu items with *ngIf:

  <button *ngIf="userType === 'admin'" mat-raised-button routerLink='application/AdminAccess/admin-activity' routerLinkActive="active">Admin Activity </button>

  <button *ngIf="userType === 'user'" mat-raised-button routerLink='application/UserManagement/add-users' routerLinkActive="active">Register User</button>