Angular CanLoad Guard Example

In this tutorial, we will show you how to make use of Angular Canload Guard with an example. The Angular Route Guards are used to control, whether the user can navigate to or away from a given route. The canload guard determines whether a particular lazy loaded child route can be loaded.

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

The Angular modules can be either eagerly loaded or lazy loaded. By default Angular loads all the modules eagerly. To lazy load a module we need to use the loadChildren in the route definition

For Example, the following route loads the AdminModule lazily. Angular loads it only when the user navigates to the admin route.

Sometimes, we want to prevent the loading of the modules for unauthorized users. This is where we use the CanLoad Guard.

CanLoad Guard

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 navigate to any of the routes of the module and also stop then even see the source code of the module.

The Angular provides canActivate Guard, which prevents unauthorized user from accessing the route. But it does not stop the module from being downloaded. The user can use the chrome developer console to see the source code. The CanLoad Guard prevents the module from being downloaded.

How to use CanLoad Guard

First, we need to create a Angular Service, which implements the CanLoad Interface

The service must implement the canLoad method. This method must return either true or false. The Angular evaluates the canLoad and loads the lazy loaded module only if it returns true.

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

Next, we need to register the Service in the Root Module.

Finally, we need to add the guards to the lazy loaded routes as shown below. Note that you can create more than one CanLoad guard, each guard runs in the order added.

CanLoad Guard Example

Create a new angular app with two modules AdminModule & TestModule. Let us build a CanLoad Guard, which stops AdminModule from loading.

First, we build a AuthGuardService which Implements the CanLoad Interface as shown below.

In the canLoad method check if the route is admin and return false else return true. In real life application, you can use dependency injection to inject the authentication service and check to see if the user is authorized or not.

Next, in the route definition include AuthGuardService under canLoad.

Finally, register the service in the AppModule.

Run the Application. Open the developer console and you will see that only test module is downloaded and not admin module.

Complete Example















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