Wednesday, September 4, 2024

Route Guards in Angular

Route Guards in Angular

When building Angular applications, managing access to different routes is crucial for both security and user experience. Angular provides a robust mechanism called Route Guards to control navigation. Let’s dive into what Route Guards are, the different types available, and how to implement them with examples.

What are Route Guards?

Route Guards are interfaces that allow you to control the navigation to and from routes in your Angular application. They help you decide whether a user can access a particular route or not. There are several types of Route Guards:

  • CanActivate: Determines if a route can be activated.
  • CanActivateChild: Determines if child routes can be activated.
  • CanDeactivate: Determines if a route can be deactivated.
  • CanLoad: Determines if a module can be loaded.
  • CanMatch: Determines if a route can be matched.

Implementing CanActivate Guard

The CanActivate guard is used to check if a user can navigate to a route. Here’s an example where we use an authentication service to check if the user is logged in.

Step 1: Create the Auth Service

First, create an authentication service that will handle the login logic.

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

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isLoggedIn = false;

  login() {
    this.isLoggedIn = true;
  }

  logout() {
    this.isLoggedIn = false;
  }

  isAuthenticated(): boolean {
    return this.isLoggedIn;
  }
}
Step 2: Create the CanActivate Guard

Next, create the guard that implements the CanActivate interface.

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;
    }
  }
}
Step 3: Apply the Guard to Routes

Finally, apply the guard to the routes in your routing module.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { AuthGuard } from './auth.guard';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Other Types of Guards

CanActivateChild

This guard works similarly to CanActivate but applies to child routes.

import { Injectable } from '@angular/core';
import { CanActivateChild } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthChildGuard implements CanActivateChild {

  constructor(private authService: AuthService) {}

  canActivateChild(): boolean {
    return this.authService.isAuthenticated();
  }
}
CanDeactivate

This guard is used to prevent users from leaving a route if certain conditions are not met, such as unsaved changes.

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 CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {

  canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

Conclusion

Route Guards in Angular are powerful tools for managing access to different parts of your application. By using guards like CanActivate, CanActivateChild, and CanDeactivate, you can enhance the security and user experience of your app. Implementing these guards is straightforward and can be customized to fit your specific needs.

Happy coding!! 😊

No comments:

Post a Comment

^ Scroll to Top