CanLoad Guard in Angular Tutorial 🎯

beginner
9 min

CanLoad Guard in Angular Tutorial 🎯

Welcome to our comprehensive guide on Angular's CanLoad Guard! This tutorial is designed to help both beginners and intermediate learners understand and implement this powerful Angular feature. Let's dive in!

What is CanLoad Guard? 📝

In Angular, CanLoad Guards are used to control the navigation flow of a route. They determine whether a route should be loaded or not based on certain conditions, such as user authentication or data availability.

Why Use CanLoad Guard? 💡

CanLoad Guards are crucial for securing routes that require authentication. By using a CanLoad Guard, you can ensure that only authenticated users can access sensitive routes, enhancing the security of your Angular application.

Setting Up a CanLoad Guard 🎯

  1. First, create a new service for the CanLoad Guard:
bash
ng generate service guards/authGuard
  1. Implement the CanLoad interface in your new service:
typescript
// src/app/guards/auth.guard.ts import { Injectable } from '@angular/core'; import { CanLoad, Route, UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanLoad { canLoad( route: Route, segments: UrlSegment[], next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { // Implement your logic here to decide whether to load the route or not // For now, let's return true to allow the route to load return true; } }
  1. Now, register the CanLoad Guard in your Angular module:
typescript
// src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuard } from './guards/auth.guard'; const appRoutes: Routes = [ { path: 'secure', loadChildren: () => import('./secure/secure.module').then(m => m.SecureModule), canLoad: [AuthGuard] // Register the CanLoad Guard for the 'secure' route } ]; @NgModule({ // ... imports: [ RouterModule.forRoot(appRoutes) ] }) export class AppModule { }

Enhancing the CanLoad Guard 💡

To make the CanLoad Guard more effective, you can implement the logic to check for user authentication:

typescript
// src/app/guards/auth.guard.ts import { Injectable } from '@angular/core'; import { CanLoad, Route, UrlSegment, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from '../services/auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanLoad { constructor(private authService: AuthService) {} canLoad( route: Route, segments: UrlSegment[], next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { // Check if the user is authenticated if (this.authService.isAuthenticated()) { return true; } else { // If not authenticated, redirect to the login page this.authService.redirectToLogin(); return false; } } }

Practical Example 💡

Here's a practical example of using CanLoad Guard to protect a route that requires user authentication:

  1. Create a new Angular component for the login page:
bash
ng generate component login
  1. Update your routing to include the login component:
typescript
// src/app/app.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuard } from './guards/auth.guard'; import { LoginComponent } from './login/login.component'; const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'secure', loadChildren: () => import('./secure/secure.module').then(m => m.SecureModule), canLoad: [AuthGuard] } ]; @NgModule({ // ... imports: [ RouterModule.forRoot(appRoutes) ] }) export class AppModule { }
  1. Implement user authentication in your AuthService:
typescript
// src/app/services/auth.service.ts import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthService { private isAuthenticated = false; constructor(private router: Router) {} login() { this.isAuthenticated = true; } logout() { this.isAuthenticated = false; } isAuthenticated(): boolean { return this.isAuthenticated; } redirectToLogin() { this.router.navigate(['/login']); } }

Now, when a user tries to access the /secure route without being authenticated, they will be redirected to the login page instead.

Quiz 📝

Question: What is the purpose of CanLoad Guards in Angular?

A: To manage data loading for routes B: To control navigation flow of a route based on certain conditions C: To create Angular services

Correct: B Explanation: CanLoad Guards are used to control the navigation flow of a route based on certain conditions, such as user authentication or data availability.


That's all for today! You've learned about CanLoad Guards and how to implement them in your Angular applications. In the next lesson, we'll delve deeper into using CanLoad Guards for authentication and data loading. Stay tuned! 🎯