0
0
Angularframework~30 mins

Route guards (canActivate, canDeactivate) in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Route Guards with canActivate and canDeactivate in Angular
📖 Scenario: You are building a simple Angular app with two pages: a Dashboard and a Profile. You want to protect the Dashboard so only logged-in users can access it. Also, when users try to leave the Profile page with unsaved changes, you want to warn them before they leave.
🎯 Goal: Build route guards using canActivate to protect the Dashboard route and canDeactivate to warn users about unsaved changes on the Profile page.
📋 What You'll Learn
Create a boolean variable isLoggedIn to simulate user login status
Create a canActivate guard that allows navigation only if isLoggedIn is true
Create a canDeactivate guard that asks for confirmation if there are unsaved changes
Apply these guards to the Angular routes for Dashboard and Profile respectively
💡 Why This Matters
🌍 Real World
Route guards are used in real apps to protect pages from unauthorized access and prevent data loss by warning users before leaving pages with unsaved changes.
💼 Career
Understanding route guards is essential for Angular developers to build secure and user-friendly web applications.
Progress0 / 4 steps
1
Set up the login status variable
Create a boolean variable called isLoggedIn in the auth.service.ts file and set it to false to represent the user not logged in.
Angular
Need a hint?

Think of isLoggedIn as a simple switch that tells if the user is logged in or not.

2
Create the canActivate guard
In auth.guard.ts, create a class AuthGuard that implements CanActivate. Add a method canActivate() that returns this.authService.isLoggedIn. Inject AuthService in the constructor.
Angular
Need a hint?

Remember to inject AuthService in the guard's constructor to access isLoggedIn.

3
Create the canDeactivate guard
Create a CanComponentDeactivate interface with a method canDeactivate() that returns boolean or Promise<boolean>. Then create a PendingChangesGuard class implementing CanDeactivate<CanComponentDeactivate>. In canDeactivate(), call the component's canDeactivate() method. Inject nothing.
Angular
Need a hint?

The guard calls the component's canDeactivate() method to check if navigation away is allowed.

4
Apply guards to routes
In app-routing.module.ts, add routes for DashboardComponent and ProfileComponent. Protect the Dashboard route with canActivate: [AuthGuard]. Protect the Profile route with canDeactivate: [PendingChangesGuard]. Import the guards and components properly.
Angular
Need a hint?

Use canActivate and canDeactivate arrays in the route definitions to apply the guards.