Sriks
Sriks

Reputation: 1699

Angular 4 routing default page based on role

I have defined my routes as below:

const appRoutes: Routes = [
 {
  path: 'teacher',
  component: 'TeacherComponent'
 },
{
  path: 'student',
  loadChildren: './components/student/student.module#StudentModule',
  canLoad: [AuthGuard]
},
{ path: '**',   redirectTo: '/' }
];

I want to route my default routing based on the loggedIn user role. If it's student, I want to default my path: '**' to be redirected to '/student'. Similarly for Teacher role I wanted it to default to '/teacher'. How to implement this role based navigation by defaulting route to different urls based on the role?

Upvotes: 3

Views: 2687

Answers (2)

gaurav
gaurav

Reputation: 230

{ path: "", component: LoginViewComponent, pathMatch: "full",canActivate:[AuthGuard] }

    @Injectable()
export class AuthGuard implements CanActivate {
  role: string = "A";

  constructor(private router: Router) {}

  canActivate() {
    const route = this.role === "A" ? "/home" : "/catalog";
    this.router.navigate(['/home']);
    return true;
  }
}

Upvotes: 0

DeborahK
DeborahK

Reputation: 60528

You can use a route resolver.

Here is one of mine:

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

import { Observable } from 'rxjs/Observable';

import { IMovie } from './movie';
import { MovieService } from './movie.service';

@Injectable()
export class MovieResolver implements Resolve<IMovie> {

    constructor(private movieService: MovieService) { }

    resolve(route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<IMovie> {
        const id = route.paramMap.get('id');
        return this.movieService.getMovie(+id);
    }
}

This code will prevent the route from continuing until the movie is retrieved.

You could do something similar to retrieve your roles. Then instead of simply returning, you could use the data you retrieved to activate different routes depending on the user's role.

Upvotes: 4

Related Questions