Angular Router: Using Route Guards
Join the DZone community and get the full member experience.
Join For FreeIn this article, we will be covering Route Guards and different types of route guards. Angular router’s navigation guards allow you to grant or remove access to certain parts of navigation.
Here are the below types of route guards available:
CanActivate
: It is an interface a class can implement to decide if a route can be activated or not. If all guards return true, then navigation will continue. Otherwise, navigation will be cancelled.
CanActivateChild
: It is an interface that a class can implement to decide if a child route can be activated or not. If all guards return true, then navigation will continue. Otherwise, navigation will be cancelled.
CanDeactivate
: It is an interface that a class can implement to decide if a child route can be deactivated. If all guards return true, then navigation will continue. Otherwise, navigation will be cancelled.
Resolve
: It is an interface that a class can implement to be a data provider. The interface defines aresolve()
method that will be invoked when the navigation starts. The router will then wait for the data to be resolved before the route is finally activated
CanLoad
: It is an interface that a class can implement to deciding if a child can be loaded. It is specifically useful to implement lazy loading.
You can use below command to create guard
Shell
x
1
ng generate guard guardName
This command asks which interfaces you would like to implement and depending upon that, angular-cli will create a TypeScript file with basic code structure.
Below is a code snippet that is generated when run above command.
TypeScript
xxxxxxxxxx
1
1
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
2
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; @Injectable(
3
{ providedIn: 'root' }
4
)
5
export class ActivateGuard implements CanActivate {
6
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return true;
7
}
8
}
Happy Learning!!!
Guard (information security)
AngularJS
Opinions expressed by DZone contributors are their own.
Trending
-
5 Key Concepts for MQTT Broker in Sparkplug Specification
-
Authorization: Get It Done Right, Get It Done Early
-
Introduction To Git
-
Which Is Better for IoT: Azure RTOS or FreeRTOS?
Comments