Comprehensive Guide to Angular Route Guards

Angular Route Guards are essential for controlling user access to different parts of an application based on specific conditions. These guards can be used to perform checks before a user navigates to or leaves a route, making them invaluable for use cases like authentication, data retrieval, and more. In this guide, we’ll walk you through Angular Guards and demonstrate how to implement them effectively in your Angular applications.

Understanding Angular Route Guards

Angular Route Guards give developers control over whether a user can access or leave a route. While configuring routes allows navigation between different parts of your app, it’s often necessary to limit access until the user meets certain conditions, such as logging in. Angular provides several route guards for this purpose.

A common example is using guards to restrict unauthorized users from accessing specific routes. By using the CanActivate guard, you can ensure only authenticated users can navigate to protected pages. If the user isn’t authorized, they can be redirected to a login page.

Key Use Cases of Angular Route Guards:

  1. Navigation Confirmation: Asking the user whether to save data before leaving a view.
  2. Role-Based Access Control: Restricting access to certain routes based on user roles.
  3. Route Parameter Validation: Ensuring route parameters are valid before navigation.
  4. Data Fetching: Pre-loading necessary data before displaying a component.

Types of Angular Route Guards:

Angular supports six types of route guards that help developers manage navigation control:

  1. CanActivate: Controls if a route can be activated.
  2. CanDeactivate: Determines if a user can leave a route.
  3. Resolve: Delays route activation until some data is loaded.
  4. CanLoad: Prevents the loading of a module until certain conditions are met.
  5. CanActivateChild: Controls whether a child route can be activated.
  6. CanMatch: Handles custom logic to match a route.

How to Implement Route Guards in Angular

1. CanActivate Guard

The CanActivate guard is used to determine whether a user can access a particular route. You can implement this guard to check if the user is logged in or has the necessary permissions to view a component.

Example:

@Injectable()
export class AuthGuardService implements CanActivate {
    canActivate(): boolean {
        // Check if the user is authenticated
        return true; // or false if the user is not authorized
    }
}

If the guard returns true, the route is accessible; otherwise, navigation is prevented.

2. CanDeactivate Guard

This guard is useful when you need to confirm if a user can leave a route. It’s typically used when users have unsaved changes, asking them to confirm before navigating away.

Example:

canDeactivate(): boolean {
    return confirm("Do you want to discard your changes?");
}

3. Resolve Guard

The Resolve guard ensures that certain data is fetched before the route is activated. It’s particularly useful when data from an API is needed for the route component to function.

4. CanLoad Guard

Use the CanLoad guard to prevent unauthorized users from loading specific modules. This guard stops users from downloading the code for lazy-loaded modules if they aren’t authorized.

5. CanActivateChild Guard

Similar to CanActivate, but applied to child routes, CanActivateChild ensures that a child route can only be accessed if certain conditions are met.

Steps to Implement Angular Route Guards:

  1. Create a Guard Service: Build the guard as a service by implementing the desired guard interface, like CanActivate.
import { CanActivate } from '@angular/router';
@Injectable()
export class AuthGuardService implements CanActivate {
    canActivate(): boolean {
        return true;
    }
}

Add Logic to the Guard Method: Inside the guard method, include the logic to determine whether navigation should be allowed or not.

Register the Guard in the Module: Guards are services, so you must register them in the Angular module’s providers array.

providers: [AuthGuardService],

Attach the Guard to Routes: Finally, attach the guard to the desired route in the RouterModule.

{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuardService] }

Order of Execution of Guards

When multiple guards are used in a routing hierarchy, they follow a specific order:

  1. CanDeactivate and CanActivateChild are evaluated first.
  2. CanActivate is checked next, starting from the top-most route.
  3. CanLoad is triggered when loading lazy-loaded modules.
  4. Resolve is invoked last to load necessary data.

If any guard returns false, Angular cancels the navigation.

Angular Route Guards offer powerful control over route navigation, allowing you to build secure, data-driven applications. Whether it’s authenticating users, validating data, or controlling module access, route guards can significantly enhance your app’s user experience. By mastering the various types of guards and their use cases, you can create more robust and user-friendly Angular applications.

Keep Learning 🙂

Leave a Reply

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