Member-only story
How to Add Route Guard for Angular Applications

Sometimes you might need to restrict certain pages/routes to the user, in your angular application. For instance, there might be a page that can only be supposed to accessed by logged-in users. So it would be great if we could prevent users from going to this page without login into the system. This kind of functionality can be achieved by route guards.
There are several router guards provided by angular and each one takes care of different purposes. Here we are focusing on the most common use case of router guards, preventing access of particular routes of the application to some users using canActivate route guard.
Let’s begin the journey.
- Create a new angular project using the following command.
ng new <projectName>
2. Let’s add two components to compare the changes with and without router guards. Do the following commands.
ng g c home
ng g c user
The home page is intended to be public whereas the user page is allowed only for logged-in users.
3. Create a service. This is where the logic for verifying a user lies. Use the following command to create the service. You can give any name you want.
ng g s auth