What is Route Guard in Angular ?
Route guards in an Angular application facilitates to block a particular route based on user authentication or on some extra permissions.
In this blog, we will implement route guards in Angular. Let’s suppose that dashboard page in Angular application can not be accessed until a valid user is logged in.
If someone is trying to access dashboard page directly without providing valid user credentials, in this condition we can use route guard to block that URL and then redirect that user to some other page.
Methods in Route Guard
Route Guard in Angular offers 2 methods canActivate() and canDecativate().
Most of the time canActivate() method is used to block a route in an application.
Creating Route Guards in Angular application
Implement Route Guard in Angular step by step
1. In this demo, I have created 2 components with name- dashboard and unauthorize
2. Next, I have created a route guard with below command –
ng g g /guard/userguard
It will create 2 files
CREATE src/app/guard/userguard.guard.spec.ts
CREATE src/app/guard/userguard.guard.ts
Read:- Angular Interview Questions
3. Then, import guard name in app.module.ts file
and add it to provider –
4. Next, import this guard in app-routing.module.ts file
5. Now, define the route with route guard in app-routing.module.ts file-
Above route says, DashboardComponent can only be displayed if canActivate method of Userguard returns true.
6. In our final step we will modify the Userguard.ts file
I have assigned a value to user i.e. user’s email id. That can be fetched from an API.
Then check the value for user, if it is matches the record then return true else navigate to access denied page and return false.
First create a property of type Router in constructor, then write logic in canActivate() method.
Please share this blog on social media and give your feedback in comment box below.
You may like other blogs –
Interview Questions and Answers Series –
MVC Interview Questions and Answers
Web API interview questions and answers
Keep following – SharePointCafe.Net
Prev – Routing in Angular 7
Next – Binding in Angular 7