{{announcement.body}}
{{announcement.title}}

Angular Router: Using Route Guards

DZone 's Guide to

Angular Router: Using Route Guards

Angular router’s navigation guards allow you to grant or remove access to certain url paths. We'll cover Route Guards and their different types.

· Web Dev Zone ·
Free Resource

In 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:

  1. 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.
  1. 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.
  1. 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.
  1. Resolve: It is an interface that a class can implement to be a data provider. The interface defines a resolve() 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
  1. 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

 

Happy Learning!!!

Topics:
angular, angular route, route guards, tutorial, web dev

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}