Angular Route Guards
We use the Angular Guards to control, whether the user can navigate to or away from the current route.
Uses of Angular Route Guards
- To Confirm the navigational operation
- Asking whether to save before moving away from a view
- Allow access to certain parts of the application to specific users
- Validating the route parameters before navigating to the route
- Fetching some data before you display the component.
Types of Route Guards
- CanActivate - If a Route can be accessed or not?
- CanDeactivate - If Current Route can be leaved or not?
- Resolve - Load or perform some operations before entering Route
- CanLoad - This guard works similar to CanActivate guard with one difference. The CanActivate guard prevents a particular route being accessed. The CanLoad prevents entire lazy loaded module from being downloaded, Hence protecting all the routes within that module.
- CanActivateChild - This guard determines whether a child route can be activated. This guard is very similar to CanActivateGuard. We apply this guard to the parent route. The Angular invokes this guard whenever the user tries to navigate to any of its child route.
Implementing RouteGuards
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';
@Injectable()
`export class ProductGuardService implements CanActivate {
constructor(private _router:Router ) {
}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
console.log("canActivate"); //return true
//remove comments to return true
alert('You are not allowed to view this page. You are redirected to Home Page');
this._router.navigate(["home"]);
return false;
} }`
Top comments (0)