Protecting routes
One of the essential features of Angular is router guards. Guards are helpful if we want to protect our routes from being accessed directly without authentication or prevent the user from losing changes when navigating accidentally from the route.
Guards are interfaces provided by Angular that allow us to control the accessibility of a route with a provided condition. These are applied directly to the routes we want to protect.
Let’s have a look at some of the guards provided by Angular:
CanActivate
: This is implemented on a route we want to prevent access to.- Method signature:
canActivate(route:ActivatedRouteSnapshot, state:RouterStateSnapshot):Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree
- Method signature:
The preceding code defines the signature of the CanActivate
guard. The function accepts the ActivatedRouteSnapshot
and RouterStateSnapshot
parameters and returns an Observable
or Promise
that can be of type...