Created
March 24, 2018 08:48
-
-
Save mohammedmatar/02e5c81acc771a0e46ec73c13bc54796 to your computer and use it in GitHub Desktop.
Angular5 - role guard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router'; | |
import { Observable } from 'rxjs/Observable'; | |
import {tap} from 'rxjs/operators/tap'; | |
import {UsersDsService} from '../data-source/users-ds.service'; | |
@Injectable() | |
export class RoleGuard implements CanActivate { | |
constructor( private router: Router, private userDS: UsersDsService) {} | |
canActivate( | |
next: ActivatedRouteSnapshot, | |
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { | |
return this.userDS.getRole().map(resp => { | |
return (resp === 'admin'); | |
}).pipe( | |
tap(isAdmin => { | |
if (!isAdmin) { | |
this.router.navigate(['auth/login']); | |
} | |
}), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment