Angular Route Guards Types 🎯

beginner
23 min

Angular Route Guards Types 🎯

Welcome back to CodeYourCraft! Today, we're going to dive deep into Angular Route Guards - a powerful feature that helps secure and control access to your application's routes. Let's get started! 📝

What are Angular Route Guards? 💡

Route Guards are services that are used to control the navigation flow of an Angular application. They decide whether to allow or deny navigation to a specific route based on certain conditions, such as user authentication or data validation.

Why use Route Guards? 💡

  1. Security: Route Guards help protect sensitive routes by ensuring that only authenticated users can access them.
  2. Data Validation: Route Guards can be used to validate data before navigating to a specific route, ensuring that the user is in a valid state.
  3. Performance: By preventing unauthorized users from accessing certain routes, Route Guards help improve application performance by reducing unnecessary server calls.

Angular Route Guard Types 💡

Angular provides four types of Route Guards:

  1. CanActivate
  2. CanActivateChild
  3. CanDeactivate
  4. Resolve

Let's take a closer look at each one.

1. CanActivate 📝

CanActivate is used to decide whether to allow navigation to a route. If the guard returns true, the navigation proceeds; if it returns false, the navigation is blocked.

Here's a simple example of a CanActivate guard:

typescript
import { Injectable } from '@angular/core'; import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; @Injectable() export class AuthGuard implements CanActivate { constructor(private router: Router) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // Your authentication logic here if (localStorage.getItem('currentUser')) { return true; } this.router.navigate(['/login']); return false; } }

In this example, the guard checks if there's a current user in local storage. If there is, the navigation is allowed; if not, the user is redirected to the login page.

2. CanActivateChild 📝

CanActivateChild is similar to CanActivate, but it applies to child routes. This means that even if the parent route is activated, the child routes can still be blocked.

Here's an example of a CanActivateChild guard:

typescript
import { Injectable } from '@angular/core'; import { CanActivateChild, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; @Injectable() export class AuthChildGuard implements CanActivateChild { constructor(private router: Router) {} canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // Your authentication logic here if (localStorage.getItem('currentUser')) { return true; } this.router.navigate(['/login']); return false; } }

3. CanDeactivate 📝

CanDeactivate is used to decide whether to allow navigation away from a route. If the guard returns true, the navigation proceeds; if it returns false, the navigation is blocked. This is useful when you have a form that needs to be saved before leaving a route.

Here's a simple example of a CanDeactivate guard:

typescript
import { Injectable } from '@angular/core'; import { CanDeactivate, Component } from '@angular/core'; export class ProductComponent implements CanDeactivate { canDeactivate(): boolean | Promise<boolean> | Observable<boolean> { // Your form validation logic here if (!this.formIsDirty) { return true; } return confirm('Are you sure you want to leave?'); } }

In this example, the guard checks if the form has been modified. If it hasn't, the navigation is allowed; if it has, a confirmation dialog is shown to the user.

4. Resolve 📝

Resolve is used to load data before navigating to a route. The data is only loaded once, regardless of how many times the route is activated.

Here's an example of a Resolve guard:

typescript
import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs'; import { ProductService } from './product.service'; @Injectable() export class ProductResolver implements Resolve<any> { constructor(private productService: ProductService) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Product> { return this.productService.getProductById(route.params['id']); } }

In this example, the guard resolves a product based on the ID passed in the route parameters.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does a CanActivate guard do?

That's it for today! We hope you enjoyed learning about Angular Route Guards. Stay tuned for more tutorials on CodeYourCraft! 💡

Happy coding! 🚀