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!
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.
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.
ng generate service guards/authGuard// 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;
}
}// 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 { }To make the CanLoad Guard more effective, you can implement the logic to check for user authentication:
// 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;
}
}
}Here's a practical example of using CanLoad Guard to protect a route that requires user authentication:
ng generate component login// 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 { }AuthService:// 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.
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! 🎯