3

I'm trying to implement role based routing for my root url. For example, when user logged in, I can redirect him to User's dashboard page from login.component. Same applied for admin, also redirect to admin dashboard page through login. But how to redirect to specific dashboard using role if user opens root url?

Currently my root route points to dashboard component which parse roles and redirect to desired dashboard page, user or admin. Is there a way to eliminate dashboard component?

AppRouting.ts

export const AppRoutes: Routes = [

    {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full'
    },  

{
        path: '',
        component: AdminLayoutComponent,
        canActivate: [AuthGuard],
        canLoad: [AuthGuard],
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardModule'
            },  

DashboardRouting.ts

export const DashboardRoutes: Routes = [

    {
        path: '',
        component: DashboardRedirectComponent,
    },

Test DashboardRedirect Component:

export class DashboardRedirectComponent implements OnInit, AfterViewInit {

    constructor(private auth: AuthenticationService, private router: Router) {

        let currentUser = JSON.parse(localStorage.getItem('currentUser'));

        if (this.auth.loggedIn()) {

            if (currentUser['role'] == 'User') {
                this.router.navigate(['/dashboard/user']);
            }

            if (currentUser['role'] == 'Admin') {
                this.router.navigate(['/dashboard/admin']);
            }
        }
    }

I've tried to implement that using guards and even resolver but it didn't work out. When I open root page of my app, it navigates to dashboard and after few seconds navigates to corresponding dashboard page, but I'd like to navigate user right away and without extra component for this. Any suggestion ?

hxdef
  • 393
  • 2
  • 6
  • 15

2 Answers2

0

If you want to skip the current routing you need to return false from your guard. In your role based redirect, first check if the user is actually routing to your base component /dashboard and not to a specific route /dashboard/admin otherwise you would intercept the role based routing. Then check the roles and when you want to redirect return false to skip the actual routing.

E.g:

 canActivate (route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    const roles = this.permissionsService.getPermissions();

    switch (true) {
      case state.url !== '/home': {
        return true;
      }
      case !!roles['admin']: {
        this.router.navigate(['home', 'admin']);
        return false;
      }
      case !!roles['user']: {
        this.router.navigate(['home', 'user']);
        return false;
      }
      default: return true;
    }

  }
J. S.
  • 2,268
  • 1
  • 12
  • 27
0

You need to create a Guard name as RedirectGuard as follows:

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

@Injectable()
export class RedirectGuard implements CanActivate {
 let currentUser = null;
 let auth = null;

    constructor(private authenticationService: AuthenticationService) {
      this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
      this.auth =  authenticationService;
     }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
      //Your redirection logic goes here

      if (this.auth.loggedIn()) {

        if (currentUser['role'] == 'User') {
            this.router.navigate(['/dashboard/user']);
        }

        if (currentUser['role'] == 'Admin') {
            this.router.navigate(['/dashboard/admin']);
        }
    }
   return false;

    }
}

Use RedirectGuard Inside AppRouting.ts as follows:

path: '',
        component: AdminLayoutComponent,
        canActivate: [RedirectGuard],
        canLoad: [AuthGuard],
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardModule'
            }, 
Arun Saini
  • 6,714
  • 1
  • 19
  • 22