How to Generate CanActivate In Angular?
Last Updated :
03 Sep, 2024
In Angular, protecting routes is important to make sure that unauthorized users cannot access certain parts of your application. The CanActivate interface allows you to implement route guards that determine whether a route can be activated based on specific conditions, such as user authentication or permissions. By creating a service that implements CanActivate, you can control access to your routes.
Prerequisites
CanActivate in Angular
In Angular, CanActivate
is a route guard used to determine if a route can be activated. It helps protect routes from unauthorized access. You implement it by creating a service that implements the CanActivate
interface and then use it in the route configuration.
Syntax:
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
return this.checkAuthenticationStatus();
}
Approach To Generate CanActivate In Angular
- Use the Angular CLI command
ng generate guard <guard-name>
to create a new guard. This command will generate a TypeScript file with boilerplate code that implements the CanActivate
interface. The guard is a service that will control whether or not a route can be activated. - In the newly created guard file, you'll find a method named
canActivate
. This method should contain the logic that determines whether the route should be accessible. Typically, this logic might involve checking if the user is authenticated or has the necessary permissions. - After implementing the guard's logic, you'll need to use it in your routing module. In your
app-routing.module.ts
file, import the guard and apply it to the routes you want to protect by adding the canActivate
property to the route configuration. - The guard should include logic to check conditions like whether the user is logged in, has a valid token, or meets specific criteria. This might involve checking values stored in services, local storage, or making API calls.
Steps to Generate CanActivate in Angular
Step 1: Install Angular CLI
If you haven’t installed Angular CLI yet, install it using the following command
npm install -g @angular/cli
Step 2: Create a New Angular Project
ng new can-activate
cd can-activate
Step 3: Generate CanActivate
Guard
You can generate a CanActivate guard using Angular CLI:
ng generate guard auth
Step 4: Generate Service
You can generate a Service using Angular CLI:
ng generate service auth
Step 5: Create Components
ng generate component home
ng generate component login
Folder Structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^18.1.4",
"@angular/common": "^18.1.4",
"@angular/compiler": "^18.1.4",
"@angular/core": "^18.1.4",
"@angular/forms": "^18.1.4",
"@angular/platform-browser": "^18.1.4",
"@angular/platform-browser-dynamic": "^18.1.4",
"@angular/router": "^18.1.4",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
}
Example: Create the required files as seen in the folder structure and add the following codes.
App Component Code
Below mentioned is the App Component which is the first component which gets loaded which an Angular Application is built. It initalizes all other components in order to run them.
HTML
<!-- src/app/app.component.html -->
<div style="text-align: center;">
<h1 style="color: green;">GeeksforGeeks</h1>
<h3>Generate CanActivate in Angular</h3>
<router-outlet></router-outlet>
</div>
JavaScript
// src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from './auth.guard';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
JavaScript
// src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'can-activate';
}
JavaScript
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
LoginComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Home Component Code
Below mentioned is the HomeComponent code in Angular, demonstrating how to protect a route using the CanActivate guard and providing a logout functionality. The component includes a button that triggers the logout method to log the user out.
HTML
<!-- src/app/home/home.component.html -->
<h3>Welcome to the Home Page</h3>
<p>This page is protected by CanActivate guard.</p>
<button (click)="logout()">Logout</button>
JavaScript
// src/app/home/home.component.ts
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent {
constructor(private authService: AuthService) { }
logout() {
this.authService.logout();
}
}
Login Component Code
Below mentioned is the LoginComponent code in Angular, where the user can log in to access protected routes. Upon successful login, the user is redirected to the home page.
HTML
<!-- src/app/login/login.component.html -->
<h3>Login Page</h3>
<p>Please log in to access protected routes.</p>
<button (click)="login()">Login</button>
JavaScript
// src/app/login/login.component.ts
import { Component } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
constructor(private authService: AuthService, private router: Router) { }
login() {
this.authService.login();
this.router.navigate(['/']);
}
}
CanActivate
Guard
Below mentioned is the AuthGuard code in Angular, where the CanActivate guard checks the user's authentication status before allowing access to a route. If the user is not authenticated, they are redirected to the login page.
JavaScript
// src/app/auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) { }
canActivate(): Observable<boolean> | Promise<boolean> | boolean {
return this.authService.isAuthenticated$.pipe(
map((isAuthenticated: boolean) => {
if (!isAuthenticated) {
this.router.navigate(['/login']);
return false;
}
return true;
})
);
}
}
Services
Below mentioned is the AuthService code in Angular, which manages user authentication status using a BehaviorSubject. The service provides methods to log in, log out, and observe the user's authentication state.
JavaScript
// src/app/auth.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private authenticated = new BehaviorSubject<boolean>(false);
isAuthenticated$ = this.authenticated.asObservable();
login() {
this.authenticated.next(true);
}
logout() {
this.authenticated.next(false);
}
}
Open the terminal, run this command from your root directory to start the application
ng serve --open
Open your browser and navigate to http://localhost:4200
Output
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read