How to add router guard in Angular?
Angular Router guards are used to prevent unauthorized access to certain routes in your Angular application. There are several types of guards that you can use with the Angular Router, including canActivate, canActivateChild, canDeactivate, and canLoad.
Here is an example of how to use the canActivate guard to protect a route in your Angular application:
First, create a new guard using the Angular CLI by running the following command in your terminal:
ng generate guard authThis will create a new guard called 'auth' in your src/app/auth directory.
Open the newly created auth.guard.ts file and add the following code:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}In the code above, we have created a guard called 'AuthGuard' that implements the 'CanActivate' interface. The 'CanActivate' interface requires that we implement the 'canActivate' method.
In the 'canActivate' method, we first check if the user is logged in using the 'isLoggedIn()' method from our 'AuthService'. If the user is not logged in, we redirect them to the login page using the 'navigate()' method from the Angular Router and return false.
If the user is logged in, we return true to allow access to the protected route.
Next, we need to use our 'AuthGuard' in our route definition. Open the 'app-routing.module.ts' file and modify the route definition for the protected route as follows:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProtectedComponent } from './protected/protected.component';
import { AuthGuard } from './auth/auth.guard';
const routes: Routes = [
{ path: 'protected', component: ProtectedComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
In the code above, we have modified the route definition for the protected route to include the canActivate property with the value of our 'AuthGuard' array.Now, if a user tries to access the protected route without being logged in, they will be redirected to the login page.
Angular Router guards provide an important mechanism for controlling access to routes in an application. The article explains how guards such as canActivate, canActivateChild, canDeactivate, and canLoad can be used to prevent unauthorized users from reaching protected pages. The canActivate example demonstrates how authentication status can be checked before allowing navigation.
ReplyDeleteThe step-by-step use of the Angular CLI command to generate an authentication guard provides a practical starting point for developers learning route protection through Angular Online Training. The example also shows how AuthService and Angular's Router can work together inside the guard.
The AuthGuard implementation demonstrates the use of ActivatedRouteSnapshot, RouterStateSnapshot, Observable, Promise, and UrlTree as possible return types from canActivate. Understanding these TypeScript types can help developers work more confidently with Angular routing and authentication logic through TypeScript Online Training.
ReplyDeleteRoute protection is also an important feature when developing applications that contain user accounts, dashboards, administrative pages, or other restricted functionality. The concepts discussed in the article can therefore be applied to practical Angular Projects that require controlled navigation and authentication-aware routing.
ReplyDelete