- Get link
- X
- Other Apps
Agenda:-
- What is guard
- Types of guard
- How to use
What is Guard:-
Guards in Angular are nothing but the functionality, logic which are executed before the route is loaded or the ones leaving the route beasically it's protecting our route.
Excecuting some amount of code before loading route or leaving route.
Types of Guard:-
- CanActivate guard (It checks route access).
- CanActivateChild guard (It checks child route access).
- CanDeactivate guard (Prompt for unsaved changes).
- CanLoad guard (Check before loading feature module assets).
CanActivate Guard
Create a new guard say auth.guard.ts as below. If the Auth Guard returns false then the user is not able to navigate to Login route in below example.
auth.guard.ts
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree }
from '@angular/router';
import { Observable } from 'rxjs';
import jwt_decode from "jwt-decode";
import { AppConstants } from '../constents/constent';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot)
: Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
let isvalid: boolean = false;
const token = localStorage.getItem(AppConstants.Token);
if (token) {
const decoded = jwt_decode(token) as any;
isvalid = (new Date(0).setUTCSeconds(decoded ? decoded['exp'] : 0)).valueOf() >
(new Date(0)).valueOf();
}
if (!isvalid) {
this.router.navigate(['/auth']);
}
return isvalid;
}
}
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { AuthGuard } from './share/guard/auth.guard';
const routes: Routes = [
{ path: 'auth', loadChildren: () => import('./components/auth/auth.module')
.then((m) => m.AuthModule) },
{ path: '', canActivate: [AuthGuard], component: HomeComponent, pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
CanActivateChild Guard
CanActivateChild function that checks whether the current user has permission to activate the requested child route.
CanActivateTeam.guard.ts
class UserToken {}
class Permissions {
canActivate(user: UserToken, id: string): boolean {
return true;
}
}
@Injectable()
class CanActivateTeam implements CanActivateChild {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
return this.permissions.canActivate(this.currentUser, route.params.id);
}
}
app-routing.module.ts
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'root',
canActivateChild: [CanActivateTeam],
children: [
{
path: 'team/:id',
component: TeamComponent
}
]
}
])
],
providers: [CanActivateTeam, UserToken, Permissions]
})
class AppModule {}
CanDeactivate Guard:-
CanDeactivate function that checks whether the current user has permission to deactivate the requested route.@Injectable()
class CanDeactivateTeam implements CanDeactivate<TeamComponent> {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canDeactivate(
component: TeamComponent,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
return this.permissions.canDeactivate(this.currentUser, route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
canDeactivate: [CanDeactivateTeam]
}
])
],
providers: [CanDeactivateTeam, UserToken, Permissions]
})
class AppModule {}
CanLoad:-
CanLoad function that decides whether the current user has permission to load requested child routes.class UserToken {}
class Permissions {
canLoadChildren(user: UserToken, id: string, segments: UrlSegment[]): boolean {
return true;
}
}
@Injectable()
class CanLoadTeamSection implements CanLoad {
constructor(private permissions: Permissions, private currentUser: UserToken) {}
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise<boolean>|boolean {
return this.permissions.canLoadChildren(this.currentUser, route, segments);
}
}
Route:
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamComponent,
loadChildren: 'team.js',
canLoad: [CanLoadTeamSection]
}
])
],
providers: [CanLoadTeamSection, UserToken, Permissions]
})
class AppModule {}
Comments
Post a Comment
if you have questions please let me know