/ AngularJS

Guarding Your Routes In Angular

Whenever building an application, it is important to make sure, that only the desired users are having access and not anyone else! :)
I was exploring on how I can implement this in my Angular application and that's when I found out about 'CanActivate'.
This is a class which can be injected along with it's canActivate() method. It works similar to an interface which returns a boolean(true or false)
Let me show you a small example on how it works in my angular application :

I have a service called 'AuthService', which implements for user login, logout, and the list of users from firebase using the appUser$ Observable.

auth-service

Now, I want to check for admin users before logging into an application. So, I built a guard called 'admin-auth-guard'
which implements the 'canActivate' method.

admin-auth-guard

Here, I have injected the AuthService into my AdminAuthGuard.
The canActivate() method is taking the list of users from appUser$ aquired from AuthService and mapping them to check if they have 'isAdmin' property or not.
If yes, it will return true and vice-versa.

Once this is done, I will assign the guard to my routes using canActivate in my App module.

guard-routes-1

Once the 'canActivate' receives a true value from guard services, it will allow navigation to the particular route.

Guarding Your Routes In Angular
Share this

Subscribe to Rujuta Mahindrakar