2

In my angular 8 application, I have 3 lazy-loading modules. Each module is for a specific user's role. I'm using canActivate interface for Auth and Role Guard.
For the following route

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

how should I use redirectTo property, so it redirects to a lazyloaded route based on user role . This is the code for routing module.

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path : '' , pathMatch: 'full' , redirectTo : ''},  
  { path : 'admin'  , loadChildren : () => import('./modules/admin/admin.module').then(mod => mod.AdminModule) , canActivate : [AuthGuardService] , data : { role : 'admin'}} ,
  { path : 'member' , loadChildren : () => import('./modules/member/member.module').then(mod => mod.MemberModule) , canActivate : [AuthGuardService] ,   data : { role : 'member'}} ,
  { path : 'user'   , loadChildren : () => import('./modules/user/user.module').then(mod => mod.UserModule) , canActivate : [AuthGuardService] , data : { role : 'user'}} ,

  { path : '**' , component : NotFoundComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

AuthGuardService.ts

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  constructor(
      private router: Router,
      private authService: AuthService
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
    const currentUser = this.authService.userVal;
    const role       = route.data.role;
    if (currentUser) {      
      if(role && role.indexOf(currentUser.role) > -1)
        return true;          
      else 
        return false;          
    }
    return false;
  }
}
ImFarhad
  • 2,669
  • 2
  • 18
  • 30
  • There was a feature request for this quite a while ago. The discussion and optional alternatives are listed here: https://github.com/angular/angular/issues/13373 – DeborahK Aug 06 '19 at 23:25

2 Answers2

5

once again thanks to @DeborahK. After going through this Github Disucssion, This is the workaround which works.

app.routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  { path : '' , pathMatch: 'full' , redirectTo : '' , canActivate : [RedirectGuardService]},  
  { path : 'admin'  , loadChildren : () => import('./modules/admin/admin.module').then(mod => mod.AdminModule) , canActivate : [AuthGuardService] , data : { role : 'admin'}} ,
  { path : 'member' , loadChildren : () => import('./modules/member/member.module').then(mod => mod.MemberModule) , canActivate : [AuthGuardService] ,   data : { role : 'member'}} ,
  { path : 'user'   , loadChildren : () => import('./modules/user/user.module').then(mod => mod.UserModule) , canActivate : [AuthGuardService] , data : { role : 'user'}} ,

  { path : '**' , component : NotFoundComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

redirect-guard.service.ts

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

@Injectable({
  providedIn: 'root'
})
export class RedirectGuardService implements CanActivate {
  constructor(
      private router: Router,
      private authService: AuthService
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<boolean> | Promise<boolean> | boolean {
    const user = this.authService.userVal;
    if (user) {      
      this.router.navigate(['/'+ user.role]);
      return true;      
    }      
    this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
    return false;
  }
}
ImFarhad
  • 2,669
  • 2
  • 18
  • 30
  • How can you achieve this if the same route has to be accessed by two roles? And will this work for child routes? ```{ path: '',canActivate: [AuthGuard],component:SideNavComponent,children: [ 4 child routes here with lazy load components]``` – Sai Manoj Jun 12 '20 at 15:57
  • you can pass multiple roles like this. { path : 'user-member' , loadChildren : () => import('./modules/user-member/user-member.module').then(mod => mod.UserMemberModule) , canActivate : [AuthGuardService] , data : { roles : ['user', 'member']}} , and check logged in user's role with this roles array in AuthGuard Service. And answer to your question for above route object is YES, it will work. – ImFarhad Jun 17 '20 at 08:24
1

Use this line and tell me. You have to use router constructor.

this.router.navigate(['site/home');
  • what if user is on default url. like on localhost if user is at : http://localhost:4200 , User should be redirected to a lazy-loading module but based on its role. – ImFarhad Aug 05 '19 at 11:22
  • you are not getting my point. After login ,When no **routerLink** is specified in the URL, Like http://localhost:4200 and user role is **admin** , there should be a router path which shows the default component of **admin lazy-module**. – ImFarhad Aug 05 '19 at 17:08