Understanding the CanLoad Guard in Angular: Real-time Example

Introduction:

In Angular, guards are used to protect routes and prevent unauthorized access to certain parts of your application. The CanLoad guard is a specific type of guard that prevents lazy-loaded modules from being loaded if certain conditions are not met.

In this post, we’ll explore the concept of the CanLoad guard in Angular, how it works, and provide a real-time example of when to use it.

Understanding the CanLoad Guard in Angular:

What is the CanLoad Guard in Angular?

An Angular route guard, the CanLoad guard, prevents lazy-loaded modules from loading if specific conditions are not satisfied.

When a user navigates to a route that is protected by the CanLoad guard, the guard checks whether the necessary conditions have been met before allowing the lazy-loaded module to be loaded.

How Does the CanLoad Guard Work in Angular?

Angular implements the CanLoad guard as a function that returns a boolean value or a Promise/observable that resolves to a boolean value.

When a user navigates to a protected route, the guard executes the function to determine whether the lazy-loaded module can be loaded. The guard’s decisiUnderstanding the CanLoad Guard in Angular: on is based on the function’s return value.

To implement the CanLoad guard in Angular, you need to:

  1. Create a CanLoad guard service.
  2. Implement the canActivate() method in the guard service to check whether the necessary conditions have been met.
  3. Add the CanLoad guard to the protected route.

Real-time Example of When to Use the CanLoad Guard:

Suppose your Angular application has a dashboard feature that loads lazily. You intend to restrict the dashboard from loading unless the user is authenticated and possesses the necessary permissions In this case, you can use the CanLoad guard to prevent the dashboard from being loaded until the user is authenticated and authorized.

To implement the CanLoad guard in this scenario, follow these steps:

Step 1:

Create a CanLoad Guard Service Create a new Angular service for the CanLoad guard, for example:

import { Injectable } from '@angular/core';
import { CanLoad, Route, UrlSegment } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class DashboardCanLoadGuard implements CanLoad {
  constructor(private authService: AuthService) {}

  canLoad(route: Route, segments: UrlSegment[]): boolean | Promise<boolean> {
    return this.authService.isAuthenticated() && this.authService.hasPermission('dashboard');
  }
}

Step 2:

Implement the CanLoad() Method In the CanLoad() method of the CanLoad guard service, implement the necessary checks to determine whether the lazy-loaded module can be loaded. In this example, we check whether the user is authenticated and has the ‘dashboard’ permission.

Step 3:

Add the CanLoad Guard to the Protected Route In your app-routing.module.ts file, add the CanLoad guard to the protected route, for example:

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { 
    path: 'dashboard', 
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule),
    canLoad: [DashboardCanLoadGuard]
  }
];

For more details, visit the official site of Angular.

Application Source Code @ LearnSmartCoding GitHub

Check out other topics that might interest you.

Conclusion:

The CanLoad guard in Angular is a powerful tool for protecting lazy-loaded modules and preventing unauthorized access to parts of your application. By implementing the CanLoad guard, you can ensure that only users with the necessary permissions can access certain features or sections of your application. Use this guard in combination with other guards,

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights