as a comment Rahula says that one solution out of the box is more likely that you want a Guard ..
Remember that protection is only for ROUTING .. so that only to check whether the user can access the route or not ... but not display one element in the component based on roles or something else .. for this I suggest you use *ngIf or show mapping / mapping or some user interface elements ...
For a single Role-based Guard (not only if auth is used or not) .. you can do something like:
import { Injectable } from "@angular/core"; import { AuthService, CurrentUserService } from "app/shared/services"; import { Router, RouterStateSnapshot, ActivatedRouteSnapshot, CanActivate } from "@angular/router"; import { AspNetUsersDTO } from "app/shared/models"; import { Observable } from "rxjs/Rx"; @Injectable() export class RoleGuard implements CanActivate { constructor(private authService: AuthService, private _currentUser: CurrentUserService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (!this.authService.isLoggedIn()) { resolve(false); return; } var currentUser: AspNetUsersDTO = new AspNetUsersDTO(); this._currentUser.GetCurrentUser().then((resp) => { currentUser = resp; let userRole = currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0].toUpperCase() : ''; let roles = route && route.data["roles"] && route.data["roles"].length > 0 ? route.data["roles"].map(xx => xx.toUpperCase()) : null; if (roles == null || roles.indexOf(userRole) != -1) resolve(true); else { resolve(false); this.router.navigate(['login']); } }).catch((err) => { reject(err); this.router.navigate(['login']); }); }); } canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { if (!this.authService.isLoggedIn()) { resolve(false); return; } var currentUser: AspNetUsersDTO = new AspNetUsersDTO(); this._currentUser.GetCurrentUser().then((resp) => { currentUser = resp; let userRole = currentUser.roles && currentUser.roles.length > 0 ? currentUser.roles[0].toUpperCase() : ''; let roles = route && route.data["roles"] && route.data["roles"].length > 0 ? route.data["roles"].map(xx => xx.toUpperCase()) : null; if (roles == null || roles.indexOf(userRole) != -1) resolve(true); else { resolve(false); this.router.navigate(['login']); } }).catch((err) => { reject(err); this.router.navigate(['login']); }); }); } }
And then you can use in your routing, for example:
{ path: 'awards-team', component: AwardsTeamComponent, canActivateChild: [RoleGuard], children: [ { path: 'admin', component: TeamComponentsAdminComponent, data: { roles: ['super-admin', 'admin', 'utente'] } }, { path: 'user', component: TeamComponentsUserComponent, data: { roles: ['utente'] } } ] }
source share