Popular Posts

July 22, 2024

How would you guard routes in Angular

 

In Angular, route guards are used to control navigation and access to routes based on certain conditions. There are several types of route guards available, each serving different purposes. Here’s a step-by-step guide on how to guard routes in Angular using different types of route guards:

Step-by-Step Guide to Guard Routes in Angular

1. Create a Route Guard Service

Create a route guard service that implements one of the following Angular route guard interfaces:

  • CanActivate: Determines if a route can be activated.
  • CanActivateChild: Determines if child routes of a route can be activated.
  • CanDeactivate: Determines if a route can be deactivated.
  • Resolve: Resolves route data before the route is activated.
  • CanLoad: Prevents lazy-loaded modules from loading asynchronously.

For example, let's create a AuthGuard that implements CanActivate:

// auth.guard.ts


import { Injectable } from '@angular/core';

import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth.service';


@Injectable({

  providedIn: 'root'

})

export class AuthGuard implements CanActivate {


  constructor(private authService: AuthService, private router: Router) {}


  canActivate(

    next: ActivatedRouteSnapshot,

    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {

    

    if (this.authService.isAuthenticated()) {

      return true;  // Allow navigation

    } else {

      // Navigate to login page or any other route

      this.router.navigate(['/login']);

      return false;  // Block navigation

    }

  }

}



How would you guard routes in Angular

2. Register the Route Guard

Once the route guard is implemented, you need to register it in your routing module (AppRoutingModule) or in the specific module where the guarded routes are defined.

// app-routing.module.ts


import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { HomeComponent } from './home.component';

import { ProfileComponent } from './profile.component';

import { AuthGuard } from './auth.guard';


const routes: Routes = [

  { path: '', component: HomeComponent },

  { path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }

];


@NgModule({

  imports: [RouterModule.forRoot(routes)],

  exports: [RouterModule]

})

export class AppRoutingModule { }


In the example above:

  • The ProfileComponent route is guarded by AuthGuard using the canActivate property.

3. Apply the Guard to Routes

Apply the guard to specific routes by adding it to the canActivate, canActivateChild, canDeactivate, resolve, or canLoad properties of the route configuration.

const routes: Routes = [

  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule), canLoad: [AuthGuard] }

];

Summary

  • Route guards in Angular allow you to control access to routes based on conditions such as authentication status, user roles, data availability, etc.
  • Implementing a route guard involves creating a service that implements one of the guard interfaces (CanActivate, CanActivateChild, etc.), checking the conditions for navigation, and returning true, false, or a UrlTree to control navigation.
  • Registering the route guard involves adding it to the canActivate, canActivateChild, canDeactivate, resolve, or canLoad properties of the route configuration in your routing module.

By using route guards effectively, you can ensure that your Angular application's routes are protected and navigated based on the defined conditions, enhancing security and user experience.


No comments:
Write comments