Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Role based navigation on same path

I've a small question regarding Angular 2 router using version 3.0.0-rc.1 I want to navigate to different home component based on user role such as AdminComponent or UserComponent. Can anyone please help in modifying below routes so that I can achieve the desired functionality?

{path: 'login', component: LoginComponent},  // <--- This redirects to '/' in case user is logged in
{
  path: '',
  component: HomeComponent,               
  canActivate: [AuthGuardService],  // <--- Check if user is logged in, else redirect to login
  children: [
    {
      path: '',
      component: AdminComponent  // <--- Want to navigate here if user role is 'admin'
    },
    {
      path: '',
      component: UserComponent  // <--- Want to navigate here if user role is 'user'
    }
  ]
}

AuthGuardService.ts

import {Injectable} from "@angular/core";
import {CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
import {AuthService} from "./auth.service";

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private authService: AuthService, private router: Router) {
  }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isLoggedIn()) {
      return true;
    }

    // Store the attempted URL for redirecting
    this.authService.redirectUrl = state.url;

    // Navigate to the login page with extras
    this.router.navigate(['/login']);
    return false;
  }
}

AuthService.ts

import {Injectable} from "@angular/core";

@Injectable()
export class AuthService {
  redirectUrl: string;

  logout() {
    localStorage.clear();
  }

  isLoggedIn() {
    return localStorage.getItem('token') !== null;
  }

  isAdmin() {
    return localStorage.getItem('role') === 'admin';
  }
}

Thanks.

like image 373
Ankush Avatar asked Aug 29 '16 03:08

Ankush


1 Answers

You can achieve it by below way.

{path: 'login', component: LoginComponent},  // <--- This redirects to '/' in case user is logged in
{
  path: '',
  component: HomeComponent,               
  canActivate: [AuthGuardService],
}

this is your home component html(home.component.html)

<app-admin *ngIf="user_role==='admin'"></app-admin>
<app-user *ngIf="user_role==='user'"></app-user>
make sure you are assigning user_role in your typescript file of home component

this is your admin component html(admin.component.html)

<div>
this is admin component
</div>

this is your user component html(user.component.html)

<div>
    this is user component
</div>

Hope, This will help you.

like image 112
Periyasamy Shanmugam Avatar answered Oct 20 '22 19:10

Periyasamy Shanmugam