Welcome to our deep dive into the CanActivate Guard in Angular! In this tutorial, we'll explore what CanActivate Guards are, why they're essential for secure routing, and learn how to create and implement them in your Angular projects. Let's get started!
CanActivate Guards are Angular services that decide whether a route should be activated or not. They're used primarily for authentication and authorization purposes, ensuring users have the necessary permissions to access specific routes.
Before we dive into CanActivate Guards, you should be familiar with:
First, let's create a new guard by generating a service:
ng generate service auth/auth-guardThis will create a new service named AuthGuard in the auth folder.
Open the newly created service and implement the CanActivate interface:
import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// Implement your logic here
return true; // Replace this with your custom logic
}
}In this example, we've imported the necessary modules and implemented the CanActivate interface. Our constructor injects the Router service, which we'll use later to redirect the user if they don't have the necessary permissions.
Next, we need to register the guard in the AppRoutingModule. Add the canActivate property to the guard and the route:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth/auth.guard';
const routes: Routes = [
{
path: 'protected',
canActivate: [AuthGuard], // Register the guard here
component: ProtectedComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }In this example, we've registered the AuthGuard for the /protected route.
Now, let's modify the canActivate method to perform some authentication logic:
import { Injectable } from '@angular/core';
import { CanActivate, Router, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router, private authService: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
return true;
}
}In this example, we've injected the AuthService and now use it to check if the user is logged in. If not, we redirect them to the login page.
Which Angular interface must a CanActivate Guard implement?
In this tutorial, we learned about the CanActivate Guard in Angular and how it's used for secure routing. We created a new guard, registered it in our routing module, and implemented some authentication logic to ensure only logged-in users can access protected routes.
We hope this tutorial has been helpful in your Angular journey! 🚀
Remember to practice, experiment, and ask questions. Happy coding! 💡🎯🚀