- read

Exploring Angular — Part 10: Route Guards

Șener Ali 37

Exploring Angular — Part 9: Route Guards

Șener Ali
Level Up Coding
Published in
3 min read21 hours ago

--

angular route guards
Angular Route Guards

If you missed the previous article on Route Parameters, you can catch up right here: Exploring Angular — Part 8: Route Parameters.

The Role of Angular Route Guards

Angular route guards are like vigilant sentinels stationed at various points in your application’s navigation flow. Their primary role is to protect specific routes from being accessed by unauthorized users or to perform additional actions before allowing a route to proceed. These guards ensure that your application remains secure and that users have the right permissions to access certain areas.

Types of Route Guards

Angular provides three types of route guards:

1. CanActivate: This guard determines if a route can be activated or not. It checks whether the user has the necessary credentials or permissions to access a particular route. If not, it can redirect the user to a login page or display an error message.

2. CanDeactivate: This guard checks if a user can leave a specific route. It’s useful for scenarios where you want to confirm user actions, such as leaving a form with unsaved changes.

3. CanLoad: This guard prevents the lazy loading of feature modules if certain conditions are not met. It’s essential for improving application performance by loading only the required modules.

Implementing Route Guards

To implement a route guard, you create a class that implements the corresponding guard interface, such as CanActivate. Here's an example of a CanActivate guard:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService) {}

canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.authService.isAuthenticated(); // Your authentication logic here
}
}