Route Guards in Angular 🎯

beginner
11 min

Route Guards in Angular 🎯

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.

What are Route Guards? 📝

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.

Creating a Route Guard 💡

Let's start by creating a simple route guard:

  1. Navigate to your Angular project's src/app folder.
  2. Create a new folder named guards and inside, create a new file called auth.guard.ts.
typescript
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.

Using the Route Guard 💡

Now that we've created our AuthGuard, let's use it in our application:

  1. Open your app-routing.module.ts file.
  2. Import the AuthGuard at the top.
typescript
import { AuthGuard } from './guards/auth.guard';
  1. Apply the guard to the protected route.
typescript
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.

Advanced Route Guards 💡

Angular offers several types of route guards, each serving different purposes. Here's a brief overview:

  1. CanActivate: Guard navigation to a route.
  2. CanDeactivate: Guard navigation away from a route.
  3. Resolve: Fetch data before navigating to a route.
  4. CanLoad: Guard lazy-loaded modules.

Quiz 💡

Quick Quiz
Question 1 of 1

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! 🎉