Angular

    Using Angular Guards for Route Protection


    Introduction

    Routes are an important feature in Angular applications that prevent users from accessing specific pages without permission. Angular route guards help in controlling navigation under certain conditions, like user authentication and authorization.

    What Are Angular Route Guards?

    Angular route guards are interfaces by which you may control navigation inside an application. They allow the application to prevent users from going to certain routes, from leaving a page, or from even loading some modules lazily.

    Types of Angular Route Guards

    There are five types of Angular guards, as follows:

    • CanActivate: stops unauthorized access to a particular route.
    • CanActivateChild: restricts the entry of the unauthorized child route.
    • CanDeactivate: It prevents users from leaving a route without confirmation.
    • Resolve: Fetches data before navigating to a route.
    • CanLoad: Prevents lazy-loaded modules from loading.

    1. Setting Up a CanActivate Guard

    A CanActivate guard is commonly used to restrict access to routes based on authentication status.

    Step 1: Generate the Guard

    ng generate guard auth

     

    Step 2: Implement the CanActivate Interface

    Modify the auth.guard.ts file:

    import { Injectable } from '@angular/core';import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';import { AuthService } from './auth.service';@Injectable({ providedIn: 'root' })export class AuthGuard implements CanActivate {constructor(private authService: AuthService, private router: Router) {}canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {if (this.authService.isAuthenticated()) {return true;} else {this.router.navigate(['/login']);return false;}}}

    2. Applying the Guard to Routes

    Modify the app-routing.module.ts file:

    import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { DashboardComponent } from './dashboard/dashboard.component';import { AuthGuard } from './auth.guard';const routes: Routes = [{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },{ path: 'login', component: LoginComponent }];@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule]})export class AppRoutingModule {}

    3. CanDeactivate Guard (Prevent Leaving Unsaved Changes)

    A CanDeactivate guard can prompt users before they leave a page with unsaved changes.

    Step 1: Create the CanDeactivate Guard

    ng generate guard unsaved-changes

     

    Step 2: Implement the CanDeactivate Interface

    Modify unsaved-changes.guard.ts:

    import { Injectable } from '@angular/core';import { CanDeactivate } from '@angular/router';import { Observable } from 'rxjs';export interface CanComponentDeactivate {canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;}@Injectable({ providedIn: 'root' })export class UnsavedChangesGuard implements CanDeactivate<CanComponentDeactivate> {canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {return component.canDeactivate ? component.canDeactivate() : true;}}

    Step 3: Apply the Guard to Routes

    Modify app-routing.module.ts:

    import { UnsavedChangesGuard } from './unsaved-changes.guard';const routes: Routes = [{ path: 'edit-profile', component: EditProfileComponent, canDeactivate: [UnsavedChangesGuard] }];

     

    Step 4: Implement the CanDeactivate Interface in the Component

    Modify edit-profile.component.ts:

    import { Component } from '@angular/core';import { CanComponentDeactivate } from '../unsaved-changes.guard';import { Observable } from 'rxjs';@Component({selector: 'app-edit-profile',templateUrl: './edit-profile.component.html',})export class EditProfileComponent implements CanComponentDeactivate {unsavedChanges = true;canDeactivate(): Observable<boolean> | boolean {return this.unsavedChanges ? confirm('You have unsaved changes. Do you really want to leave?') : true;}}

    Best Practices for Using Route Guards

    • Always return true or false in guards to allow or prevent navigation.
    • Redirect unauthorized users to proper pages, for example, the login page.
    • Use Resolve Guards when data needs to be fetched before loading a route.
    • Prevent unnecessary API calls inside guards and depend on stored authentication states.
    • Make guards lightweight and modular for good maintenance.

    Conclusion

    Angular route guards can be a more robust means to protect routes, enhancing user experience by controlling who has access in accordance with their authentication, authorization, and other data conditions. Properly applying CanActivate, CanDeactivate, CanLoad, and many other guards makes sure your application is both safe and structured appropriately.

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    Angular

    Related Center Of Excellence