How Guards Can Help You in Angular 2023

Akash Chauhan
7 min readSep 30, 2022

--

Angular guards are a feature that can help you in many ways when coding in Angular . For example, let’s say you have an important data file that you only want certain people to be able to access.

By using a guard, you can make sure that only the people with the correct permissions can view and edit the file.

Guards are directives in Angular that allow us to control the flow of access to features in our app. They can be used to block access to certain routes, or restrict what data a user can see.

In this article, we’ll explore how guards can be used in Angular to improve security and protect data.

Guards are directives in Angular that allow us to control the flow of access to features in our app.

They can be used to block access to certain routes, or restrict what data a user can see. In this article, we’ll explore how guards can be used in Angular to improve security and protect data.

Learning Objectives

In this lecture you will learn:

  • Introduction to angular guard
  • The five different types of angular guard
  • CanActivate guard
  • CanDeactivate guard
  • CanActivateChild guard
  • CanLoad guard
  • Resolve guard

Intro:

The role of angular guard is to protect routes. Guard can prevent unauthorized access to a route in angular, or they can redirect users to a different route.

An Angular Guard is a feature that helps to secure routes in your application. When a user tries to access a route that is protected by an Angular Guard, the guard will run some checks to see if the user is allowed to access the route.

If the user is allowed, they will be able to proceed. If not, they will be redirected to another page or given an error message. There are different types of Angular Guards, such as Route Guards and Auth Guards.

The most common use for angular guard is to protect Components that are lazy loaded.

When a user attempts to lazy load a Component, the router will first check if the user is authorized to access the Component.

If the user is not authorized, the router will redirect them to a different route. Guards can also be used to protect data that is being fetched from an API. If the data that is being fetched is not public, the angular guard will prevent unauthorized access and return an error message.

Five different types of Router Guard

Guard are one of the important features of Angular that helps us to control the access to the particular routes.

It is very important to understand the different types of guard because they play a vital role in securing our Angular applications.

In this article, we will be discussing the different types of guard and how they can be used to protect our Angular applications.

There are five different types of guard in Angular:

- CanActivate guard: CanActivate guard is used to decide if a route can be activated or not.

- CanDeactivate guard: CanDeactivate guard is used to decide if a route can be deactivated or not.

- CanActivateChild guard: CanActivateChild guard is used to prevent unauthorized access to child routes.

- CanLoad guard: Canload guard is used to decide if a module can be loaded or not.

- Resolve guard: Resolve resolve guard is a feature of the router that allows you to pre-fetch data before displaying a route

CanActivate guard is used to control whether a route can be activated or not. If the guard returns true, the route can be activated; otherwise, it will be blocked.

This guard is used to protect routes from being accessed by unauthorized users. They are typically used to perform authentication and authorization checks.

Lets get into an example:

Create a file with naming convention: guardName.guard.ts, inside this file we will implement the interface for CanActivate provided by Angular.

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


@Injectable()
export class AuthGuardService implements CanActivate {

constructor(private _router:Router ) {
}

canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {

//check some condition
if (yourCondition) {
alert('You are not allowed to view this page');
//redirect to login/home page etc
//return false to cancel the navigation
return false;
}
return true;
}

}

Now its time to just update the router file and see the magic :)

{ path: 'product', component: ProductComponent, canActivate : [AuthGuardService] },

One of the Guards is the CanDeactivate Guard. This guard is used to protect routes from being accidentally navigated away from.

It can be used to prompt the user for confirmation before navigating away from unsaved changes.

The CanDeactivate Guard is implemented as an interface with a single canDeactivate() method.

This method takes two arguments: the component being navigated away from and an optional activatedRouteSnapshot containing information about the route being navigated to.

The canDeactivate() method must return either true or false .

If it returns true , navigation will continue. If it returns false , navigation will be cancelled.

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

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

@Injectable()
export class CanDeactivateGuard implements CanDeactivate {

canDeactivate(component: CanComponentDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
return component.canDeactivate ? component.canDeactivate() : true;
}

}
{
path: 'product',
component: ProductComponent,
canDeactivate: [CanDeactivateGuard]
}

The CanActivateChild guard is used to protect routes that might have children. This guard is similar to the CanActivate guard, except that it takes an additional route parameter, which is the child route to be activated.

The CanActivateChild guard is invoked before any child routes are activated. If the guard returns false, or a Promise that resolves to false, then the child route will not be activated.

Otherwise, if the guard returns true, or a Promise that resolves to true, then the child route will be activated.

The CanActivateChild guard has access to the same ActivatedRouteSnapshot and RouterStateSnapshot parameters that are available to the CanActivate guard.

These parameters can be used to access information about the current route, and the router state.

{ path: 'product', component: ProductComponent, canActivate : [AuthGuardService], 
canActivateChild : [AdminGuardService],
children: [
{ path: 'view/:id', component:ItemViewComponent },
{ path: 'edit/:id', component: ItemEditComponent },
{ path: 'add', component: ItemAddComponent }
]
}

CanLoad guard

In Angular, the canLoad guard prevents a lazy-loaded module from loading if the user is not authorized. This guard is used to protect sensitive data from being accessed by unauthorized users.

The canLoad guard is implemented using the canLoad() method of the NgModule class. This method takes a route as an argument and returns a boolean value.

If the returned value is true, the module is loaded; if it is false, the module is not loaded. The canLoad guard is invoked when the user attempts to navigate to a lazy-loaded module.

If the guard returns false, the navigation is aborted and the user remains on the current page.

import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material';
import { CanLoad } from '@angular/router';
import { SomeComponent } from './shared/some/some.component';
@Injectable({
providedIn: 'root'
})
export class CanLoadGuard implements CanLoad {
constructor(private dialog: MatDialog) {}
canLoad(): boolean {
if (someCondition) {
const dialogRef = this.dialog.open(SomeComponent, {width: '400px'});
return false;
} else {
return true;
}
}
}
{
path: 'users',
loadChildren: './modules/user/user.module#userModule',
canActivate: [AuthGuard],
canLoad: [CanLoadGuard]
},

Resolve guard

When working with Angular, it’s important to know how to use the resolve guard.

The resolve guard allows you to take care of data dependencies before the component is even created. This is especially useful when you need to make an API call or load data from a file

@Injectable()
export class UserDetailResolver implements Resolve {
constructor(private userService: UserService, private router: Router) { }

resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise {
let id = route.paramMap.get('user-id') ?? '';
console.log('Resolving for person id:' + id);

return this.userService.getUser(id).then(person => {
if (person) {
return person;
} else {
this.router.navigate(['/user/userList']);
return null;
}
});
}
}
{
path: 'userList',
component: UserListComponent,
children: [
{
path: 'detail/:user-id',
component: UserDetailComponent,
resolve: {
userDetail: UserDetailResolver
}
}
]
}

Guards are a feature in Angular that help developers control access to certain parts of the application.

By using angular guard, developers can control who has access to what features, and can also customize the behavior of the application based on the user’s role.

Angular guards are one of the tools that help developers build web applications. By allowing and disallowing certain routes, they give the developer more control over how users interact with the app.

Additionally, guards can be used to protect data by only allowing certain users to access it. This makes them an important part of security for web applications.

Related topics:

What Sets Angular Apart from Other Frameworks?

Optimize your Angular architecture for peak performance 2023

What is new in angular 14 , Know what are improvements and features of v14.

Top 9 commonly used rxjs operators in angular

Originally published at https://www.akashminds.com.

--

--

Akash Chauhan

Akash Expertises in front-end technologies including javascript, Angular,Rxjs, React.js, HTML, CSS and Jquery.