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! 📝
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.
Angular provides four types of Route Guards:
Let's take a closer look at each one.
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:
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.
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:
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;
}
}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:
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.
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:
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.
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! 🚀