-1

Is there any way to implement a role-based routing in angular?

I haven't tried anything because i don't know where to start.

I have two components LandingPageComponent and AdminPageComponent. And i have basic routing module:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LandingPageComponent } from './pages/landing-page/landing-page.component';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: '/home'
  },
  {
    path: 'home',
    component: LandingPageComponent
  },
  {
    path: 'admin',
    component: AdminPageComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I also implemented JWT-based authorization and its all works just fine. But my problem is i don't know how to implement role-based routing:

For example i have 2 roles client and admin. So when client visits localhost:5000/ i want routing module to return LandingPageComponent, but when admin visits the same route routing module should return AdminPageComponent.

So my question is there any possibilities in angular to implement such routing module?

Rintales
  • 45
  • 1
  • 9

2 Answers2

0

You can add guard for path:

  {
    path: '',
    pathMatch: 'full',
    redirectTo: '/home',
    canActivate: [RoleGuard]
  }

In RoleGuard you can implemente canActivate method which will check user role and will navigate to correct path.

0

yes. Just like an auth guard you can have a role guard. It will look something like this:

@Injectable()
export class AdminGuard implements CanActivate  {
  constructor(private router: Router) { }

  canActivate() : boolean {
    let user = localStorage.getItem(role);

    if(user !== 'admin') {
      this.router.navigate(['/user']);
    } else {
      return true;
    }
  }
}

And in your router:

{ path: '', canActivate: [AuthGuard, AdminGuard], redirectTo: 'Day', pathMatch: 'full' }
Muhammad Kamran
  • 978
  • 6
  • 10