Building Guards in Angular

Introduction to Route Guards in Angular

Welcome to the lesson on building guards in Angular! In this lesson, we'll explore how route guards can help control access to different parts of your Angular application. Route guards are essential for ensuring that only authorized users can access certain routes, enhancing the security and functionality of your application. By the end of this lesson, you'll be equipped to implement basic route guards, specifically focusing on the CanActivate, CanDeactivate, Resolve, and CanMatch guards. Let's dive in! 🚀

Understanding the `CanActivate` Guard

The CanActivate guard is a powerful tool for controlling access to routes based on user authentication. It checks whether a user is allowed to navigate to a specific route. If the user is not authorized, the guard can redirect them to a different route, such as a login page.

Here's a simple example of how a CanActivate guard might be structured:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

In this example, the AuthGuard class implements the CanActivate interface. It uses an AuthService to check if the user is logged in. If the user is authenticated, the guard allows access to the route by returning true. Otherwise, it redirects the user to the login page and returns false.

Understanding the `CanDeactivate` Guard

The CanDeactivate guard is used to prevent users from accidentally leaving a route when there are unsaved changes. It prompts the user to confirm navigation away from the current route, which can help prevent data loss.

Here's an example of a CanDeactivate guard:

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';

export interface CanComponentDeactivate {
  canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
}

@Injectable({ providedIn: 'root' })
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> | boolean {
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

In this example, the guard checks if the component implements the CanComponentDeactivate interface and calls its canDeactivate method to determine if navigation should proceed.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal