CanActivate and CanActivateChild Route Guards with Angular?
This Article helps you to Understand, How To Use CanActivate and CanActivateChild Route Guards with Angular?
There are the 4 types of routing guards available:
CanActivate: Controls if a route can be activated.
CanActivateChild: Controls if children of a route can be activated.
CanLoad: Controls if a route can even be loaded. This becomes useful for feature modules that are lazy-loaded. They won’t even load if the guard returns false.
CanDeactivate: Controls if the user can leave a route. Note that this guard doesn’t prevent the user from closing the browser tab or navigating to a different address. It only prevents actions from within the application itself.
Define Simple Auth Service
Using the CanActivate and CanActivateChild Route Guard
Route guards are most often implemented as classes that implement the needed route guard interface.
Let’s consider an example with a CanActivate route guard where we ask an auth service if the user is authenticated:
Take note of how we declared a canActivate method to implement the CanActivate interface. In situations where you might need information about the current route, the method has optional access to the ActivatedRouteSnapshot and the RouterStateSnapshot.
The canActivate returns a boolean depending on if the user is authenticated or not, but it could have also returned an observable or a promise that resolve to a boolean.
In order to use them, route guards should be provided like services.so we have to register our Guard in app.module.ts
And then lastly, you’ll want to add the guard as part of your routing configuration.
import { NgModule } from "@angular/core";
Now only users that are authenticated can activate the /dashboard route.
Notice how we provide an array of guards in the route definition. This means that we could specify multiple guards for a single route, and they’ll be evaluated in the order in which they are specified.