Route guards in Angular are responsible for controlling access to specific routes based on user roles or permissions. They act as middleware, deciding whether a user can navigate to a particular route or not.
To implement authorization using route guards, follow these steps:
1. Create a custom guard by implementing the CanActivate interface.
2. Inject any required services, such as an authentication service, into the guard’s constructor.
3. Implement the canActivate() method, which returns either true (allowing navigation) or false (denying navigation). Use the injected services to determine if the user has the necessary permissions.
4. Register the custom guard in the AppModule providers array.
5. Add the custom guard to the desired route(s) in the AppRoutingModule using the ‘canActivate’ property.
Example of a custom route guard:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.authService.isAuthenticated();
}
}