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 auth
This 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.
Comments
Post a Comment