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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With