I am implementing role-based access control in my Angular application using guards. Specifically, I want to protect certain routes based on user roles. However, I’m encountering errors in my authentication guard implementation.
import { Injectable } from ‘@angular/core’;
import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from ‘@angular/router’;
import { Observable } from ‘rxjs’;
import {AuthentificationService} from “../services/authentification.service”;
@Injectable({
providedIn: ‘root’
})
export class AuthorizationGuard implements CanActivate {
constructor(private authService : AuthentificationService, private router : Router) {
}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if(this.authService.roles.include(“ADMIN”)){
return true;
}else{
this.router.navigateByUrl(“/admin/notAuthorized”)
return false;
}
}
}
core.mjs:8400 ERROR Error: Uncaught (in promise): TypeError: this.authService.roles.include is not a function
TypeError: this.authService.roles.include is not a function
Sirat Ben jemaa is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.