Angular Guards Tutorial

In this tutorial, we look at Angular Route Guards. The Angular supports several guards like CanActivate, CanDeactivate, Resolve, CanLoad, and CanActivateChild. These guards help us to secure the route or to perform some actions before navigating into a route or leaving the route. We look at all these in this tutorial on Route Guards by building an example angular guards application.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

Angular Route Guards

We use the Angular Guards to control, whether the user can navigate to or away from the current route.

Why Guards

We looked at how to configure our routes and navigate to the different parts of our application in our Angular Router Tutorial. Allowing the user to navigate all parts of the application is not a good idea. We need to restrict the user until the user performs specific actions like login. Angular provides the Route Guards for this purpose.

One of the common scenario, where we use Route guards is authentication. We want our App to stop the unauthorized user from accessing the protected route. We achieve this by using the CanActivate guard, which angular invokes when the user tries to navigate into the protected route. Then we hook into the CanActivate guard and use the authentication service to check whether the user is authorized to use the route and if not we can redirect the user to the login page.

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.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

Types of Route Guards

The Angular Router supports Five different guards, which you can use to protect the route

  1. CanActivate
  2. CanDeactivate
  3. Resolve
  4. CanLoad
  5. CanActivateChild

CanActivate

This guard decides if a route can be activated (or component gets used). This guard is useful in the circumstance where the user is not authorized to navigate to the target component. Or the user might not be logged into the system

Read: Angular CanActivate Guard Example

CanDeactivate

This Guard decides if the user can leave the component (navigate away from the current route). This route is useful in where the user might have some pending changes, which was not saved. The CanDeactivate route allows us to ask user confirmation before leaving the component.  You might ask the user if it’s OK to discard pending changes rather than save them.

Read: Angular CanDeactivate Guard Example

Resolve

This guard delays the activation of the route until some tasks are complete. You can use the guard to pre-fetch the data from the backend API, before activating the route

CanLoad

The CanLoad Guard prevents the loading of the Lazy Loaded Module. We generally use this guard when we do not want to unauthorized user to be able to even see the source code of the module.

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.

Read: Angular CanLoad Guard Example

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. This allows us to check some condition and decide whether to proceed with the navigation or cancel it.

Read: Angular CanActivateChild Guard Example

How to Build Angular Route Guards

Building the Guards are very easy.

  1. Build the Guard as Service.
  2. Implement the Guard Method in the Service
  3. Register the Guard Service in the Root Module
  4. Update the Routes to use the guards

1. Build the Guard as Service

Building the Guard Service is as simple as building any other Angular Service. You need to import the corresponding guard from the Angular Router Library using the Import statement. For Example to use CanActivate Guard import the CanActivate in the import  the CanActivate in the import statement

Next, create the Guard class which implement the selected guard Interface as shown below.

You can also inject other services into the Guards using the Dependency Injection

2. Implement the Guard Method

The next step is to create the Guard Method. The name of the Guard method is same as the Guard it implements. For Example to implement the CanActivate guard, create a method CanActivate

Return value from the Guard

The guard method must return either a True or a False value.

If it returns true, the navigation process continues. if it returns false, the navigation process stops and the user stays put.

The above method returns a True value. The Guard can also return an Observable or a Promise which eventually returns a True or false. The Angular will keep the user waiting until the guard returns true or false.

The guard can also tell the router to navigate elsewhere, effectively canceling the current navigation.

3. Register the Guard as Service in Module

As mentioned earlier, guards are nothing but services. We need to register them with the Providers array of the Angular Module as shown below

The Angular router requires the Guards and all other services that guard depends on available during the navigation. Hence the guards must be provided at the module level. This allows the router to access the guards using the Dependency Injection.

4. Update the Routes

Finally, we need to add the guards to the routes array as shown below

The above code adds the canActivate guard (ProductGuardService) to the  Product route.

When the user navigates to the Product route the Angular calls the canActivate method from the ProductGuardService. If the method returns true then the ProductComponent is rendered.

You can add more than one guard as shown below

The syntax for adding other guards are also similar

Order of execution of route guards

A route can have multiple guards and you can have guards at every level of a routing hierarchy.

CanDeactivate() and CanActivateChild() guards are always checked first. The checking starts from the deepest child route to the top.

CanActivate() guard is checked next and checking starts from the top to the deepest child route.

CanLoad() is invoked next,  If the feature module is to be loaded asynchronously.

Resolve() Guard is invoked last.

The Angular Router cancels the navigation If any of the guards return false.

Angular Guards Example

Let us update the App, we built in the previous tutorials on Angular Routers, and use theCanActivate Guard to prevent the user from activating the ProductComponent

The source code for this tutorial is available on GitHub

Guard Service

We create Guard classes are service. Create a file named product-guard.service.ts in the src/app folder and add the following code

First, we need to import the Router, CanActivate, ActivatedRouteSnapshot & RouterStateSnapshot library from the angular/core package

Define the ProductGuardService which implements the CanActivate Interface

Finally, define the canActivate method

The canActivate method accepts two arguments. The first argument is an ActivatedRouteSnapshot object, which describes the route that is being navigated to using the properties. The second argument is a RouterStateSnapshot object, which describes the current route through a single property called URL.

Import the Guard in the Root Module

First Import the Guard Service as shown below

Next, Register it using the Providers metadata, so that router can use it. Remember that Guards must be provided at the angular module level

Update the Routes

Finally, Update the app.routes class

The only change we have done is to attach the ProductGuardService to the CanActivate guard

Test the Guard Run the app and you will see the alert message “You are not allowed to view this page. You are redirected to Home Page”

Summary

The angular Guards are a great tool, which helps us to protect the route. They also help us to run some logic, get data from the back end server, etc. You can also create multiple guards against a single route or use the same guard against multiple routes.

2 thoughts on “Angular Guards Tutorial”

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top