Angular Router 11: Can Activate Guard Made Easy

Yuvaraj S
2 min readDec 15, 2022

--

In the previous blog, we discussed
Angular Router 10: Creating a separate module for Routing

Before going to Can Activate Guard, It’s essential to understand what’s guard in angular.
In Simple words guards are the protector of the Router.

By Default, We can Freely Navigate one route to another route in angular. Sometimes We don’t need navigation to the route because we might Need some Data to Navigate. In order to protect Guards Come into Picture Here. Just like a picture shown below.

Photo by Aaron Greenwood on Unsplash

Guards will only Work only Boolean value. Other than that it can take promise or a Observable, Even SO it will be taking as a Boolean as a Type. Simply True Means Navigate and False means don’t Navigate.

There Are mainly 5 Types of Guards in Angular,

  1. Can Activate: To allow the USer to USe the route
  2. Can Activate Child : To see if a user can navigate to Child routes
  3. Can Deactivate : To Exit the Route
  4. Resolve : Data retrival before route activation
  5. CanLoad : Route to a module that lazy loaded

In our current blog we will discuss Can Activate guard,
Can Activate is an interface that implements to br a guard deciding if a route can be activated.

I have created 2 components, one is login component and second is logout component.
1 Service and 1 guard, in a service file one variable we will store is it true or false,
and in our guard file we will check if the variable has true. If it has we will activate our route.

Finally we will attach the guard for a router.

Find the Working Code Here,
https://stackblitz.com/edit/angular-ivy-zydh9t

In logout.component.ts we are calling service which sets true as a value.

auth.service.ts

Create a ts file with a naming convention of _name_.guard.ts, to create a guard.

In our Guard we specify our logic. Here I took login value of Auth service as true and activating the route. If not navigate to logout component.
In our routing module we attach this guard so it can protect the guard, like avoids the navigation.

In login route we have attached our guard by adding canActivate key.

In Next Blog

Angular Router 12: Can Deactivate Guard

— — — — — — — — — End Of Lecture — — — — — — —

Check All lessons of Angular Intermediate Lessons

https://medium.com/@yuvayuvaraj720444/angular-intermediate-lessons-acbea2dfc9b

--

--

Yuvaraj S

Passionate Angular Developer. I post programming content regarding, Frontend Development with working example. ie, Angular, Html, CSS, Javascript