Wednesday, November 28, 2018

How to use Route Guard

Route Guard :- this is the concept in AngularJS which allows the developer to fix/assist Guard on the router. i.e. This Guard will first check if the user is access right to route if yes then he will be allowed to go to that url else we can take action agains it.
Lets try to understand using exmple
Step 1- Let s first create guard using ng command i.e. ng generate guard Auth or ng g g auth
Step 2- we will find following file create in our project
import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
public flag : boolean;
constructor()
{
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return true;
}
}
Step 3- configure this in our app.module.ts
providers: [ AuthService, AuthGuard],
{
path:'admin',
component:AdminComponent,
canActivate: [AuthGuard]
},
Step 4- as we can see this Guard return true so we can access /admin url by both the way i.e. using direct hit http://localhost:4200/admin or by going through programatically.
Now let see if we only want the user to get it access through programitically and not by direct hit to url i.e. http://localhost:4200/admin
To do this we had done following changes
1- On successful call to Service.ts we call this method of Auth.Guard.ts
this.myAuth.setFlagValue(true);
2- In AuthGuard.ts we have added following this method
setFlagValue(value : boolean)
{
this.flag = value;
}
and canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
//return true;
return this.flag;
}

So now when we go through programe we will be able to go to /admin url else when we hit the direct url we fails.

Note:- Code is available at
https://github.com/shdhumale/AJS6_Tutorial_Project.git

No comments: