Search code examples
angularangular-routingangular-routerangular-router-guards

Angular 6 role based routing on root url


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 ?


Solution

  • 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'
                },