Introduction
Route Guards in Angular are used to control access to routes in an application. They allow you to implement logic that determines whether a route can be activated, deactivated, loaded, or unloaded. This is particularly useful for authentication, authorization, and other conditional navigation scenarios.
Types of Route Guards
Angular provides several types of route guards:
- CanActivate: Determines if a route can be activated.
- CanActivateChild: Determines if a child route can be activated.
- CanDeactivate: Determines if a route can be deactivated.
- CanLoad: Determines if a module can be loaded lazily.
- Resolve: Pre-fetches data before activating a route.
Implementing CanActivate Guard
Step-by-Step Guide
-
Create a Guard Service: Use Angular CLI to generate a guard service.
ng generate guard auth
-
Implement CanActivate Interface: Open the generated
auth.guard.ts
file and implement theCanActivate
interface.import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; // Assume you have an AuthService @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.authService.isLoggedIn(); // Replace with your actual logic } }
-
Register the Guard in Routes: Apply the guard to routes in your
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: 'home', component: HomeComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Example: AuthService
Here is a simple example of an AuthService
that the guard might use.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthService { private loggedIn = false; login() { this.loggedIn = true; } logout() { this.loggedIn = false; } isLoggedIn(): boolean { return this.loggedIn; } }
Practical Exercise
Task
- Create a new Angular project.
- Implement an
AuthGuard
that prevents access to a protected route unless the user is logged in. - Create a simple login mechanism using
AuthService
.
Solution
-
Create a new Angular project:
ng new route-guards-demo cd route-guards-demo
-
Generate AuthGuard:
ng generate guard auth
-
Implement AuthService:
// auth.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthService { private loggedIn = false; login() { this.loggedIn = true; } logout() { this.loggedIn = false; } isLoggedIn(): boolean { return this.loggedIn; } }
-
Implement AuthGuard:
// auth.guard.ts import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { return this.authService.isLoggedIn(); } }
-
Set Up Routes:
// 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: 'home', component: HomeComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
-
Create Components:
ng generate component home ng generate component login
-
Implement Login Logic:
// 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(['/home']); } }
<!-- login.component.html --> <button (click)="login()">Login</button>
-
Test the Application:
- Start the application using
ng serve
. - Navigate to
/home
and verify that you are redirected to the login page if not logged in. - Log in and verify that you can access the home page.
- Start the application using
Conclusion
Route Guards are a powerful feature in Angular that help you control access to routes based on custom logic. By implementing guards like CanActivate
, you can ensure that only authorized users can access certain parts of your application. This module covered the basics of creating and using route guards, providing a solid foundation for more advanced routing scenarios.
Angular Course
Module 1: Introduction to Angular
- What is Angular?
- Setting Up the Development Environment
- Angular Architecture
- First Angular Application
Module 2: Angular Components
- Understanding Components
- Creating Components
- Component Templates
- Component Styles
- Component Interaction
Module 3: Data Binding and Directives
- Interpolation and Property Binding
- Event Binding
- Two-Way Data Binding
- Built-in Directives
- Custom Directives
Module 4: Services and Dependency Injection
Module 5: Routing and Navigation
Module 6: Forms in Angular
Module 7: HTTP Client and Observables
- Introduction to HTTP Client
- Making HTTP Requests
- Handling HTTP Responses
- Using Observables
- Error Handling
Module 8: State Management
- Introduction to State Management
- Using Services for State Management
- NgRx Store
- NgRx Effects
- NgRx Entity
Module 9: Testing in Angular
Module 10: Advanced Angular Concepts
- Angular Universal
- Performance Optimization
- Internationalization (i18n)
- Custom Pipes
- Angular Animations