CanActivate Guard in Angular Tutorial 🎯

beginner
7 min

CanActivate Guard in Angular Tutorial 🎯

Welcome to our deep dive into the CanActivate Guard in Angular! In this tutorial, we'll explore what CanActivate Guards are, why they're essential for secure routing, and learn how to create and implement them in your Angular projects. Let's get started!

Introduction 📝

CanActivate Guards are Angular services that decide whether a route should be activated or not. They're used primarily for authentication and authorization purposes, ensuring users have the necessary permissions to access specific routes.

Prerequisites 💡

Before we dive into CanActivate Guards, you should be familiar with:

  • Angular basics (components, services, modules, dependency injection)
  • Routing in Angular
  • Authentication and Authorization concepts

Creating a CanActivate Guard 🎯

  1. Create a new Guard

First, let's create a new guard by generating a service:

bash
ng generate service auth/auth-guard

This will create a new service named AuthGuard in the auth folder.

  1. Implementing the CanActivate interface

Open the newly created service and implement the CanActivate interface:

typescript
import { Injectable } from '@angular/core'; import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { // Implement your logic here return true; // Replace this with your custom logic } }

In this example, we've imported the necessary modules and implemented the CanActivate interface. Our constructor injects the Router service, which we'll use later to redirect the user if they don't have the necessary permissions.

Using the CanActivate Guard 🎯

  1. Registering the Guard

Next, we need to register the guard in the AppRoutingModule. Add the canActivate property to the guard and the route:

typescript
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AuthGuard } from './auth/auth.guard'; const routes: Routes = [ { path: 'protected', canActivate: [AuthGuard], // Register the guard here component: ProtectedComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }

In this example, we've registered the AuthGuard for the /protected route.

  1. Implementing the authentication logic

Now, let's modify the canActivate method to perform some authentication logic:

typescript
import { Injectable } from '@angular/core'; import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { AuthService } from '../services/auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private router: Router, private authService: AuthService) {} canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { if (!this.authService.isLoggedIn()) { this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } }); return false; } return true; } }

In this example, we've injected the AuthService and now use it to check if the user is logged in. If not, we redirect them to the login page.

Quick Quiz
Question 1 of 1

Which Angular interface must a CanActivate Guard implement?

Summary 📝

In this tutorial, we learned about the CanActivate Guard in Angular and how it's used for secure routing. We created a new guard, registered it in our routing module, and implemented some authentication logic to ensure only logged-in users can access protected routes.

We hope this tutorial has been helpful in your Angular journey! 🚀

Remember to practice, experiment, and ask questions. Happy coding! 💡🎯🚀