Welcome to our comprehensive guide on Angular's Route Guards! In this tutorial, we'll explore how route guards secure and control navigation in your Angular applications. By the end, you'll have a solid understanding of this powerful feature, perfect for both beginners and intermediates.
Route Guards are Angular services that control navigation to or within an Angular application. They're used to protect routes, guard access, and handle transitions based on certain conditions.
Let's start by creating a simple route guard:
src/app folder.guards and inside, create a new file called auth.guard.ts.import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
// Add your authentication logic here
if (/* user is authenticated */) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}In the above code, we've created a AuthGuard service and implemented the CanActivate interface. This interface requires the canActivate() method, which is called by Angular when attempting to navigate to the guarded route.
Now that we've created our AuthGuard, let's use it in our application:
app-routing.module.ts file.AuthGuard at the top.import { AuthGuard } from './guards/auth.guard';const routes: Routes = [
{ path: 'protected', canActivate: [AuthGuard], component: ProtectedComponent },
];Now, when navigating to the /protected route, the AuthGuard will check if the user is authenticated. If not, the user will be redirected to the /login route.
Angular offers several types of route guards, each serving different purposes. Here's a brief overview:
CanActivate: Guard navigation to a route.CanDeactivate: Guard navigation away from a route.Resolve: Fetch data before navigating to a route.CanLoad: Guard lazy-loaded modules.What does the `AuthGuard` do in the given example?
That's it for our Route Guards tutorial! Practice by creating more guards and securing your Angular applications effectively. Happy coding! 🎉