Angular 2 Guards To Protect Routes

There are four different guard types available, and we can use them to protect application routes before they navigate,

  • CanActivate # It decides if a route can be activated or not
  • CanActivateChild # it decides if child routes of a route can be activated or not
  • CanDeactivate # It decides if a route can be deactivated or not
  • CanLoad # It decides if a module can be loaded lazily or not

Define Guards

Guards can be implemented in different ways but after all, it returns either Promise<boolean>, Observable<boolean> or boolean. Guards can be registered, using providers and they can be injected by Angular when they needed.

Guards as Functions

We should define a token and the guard function to register a guard. Here is the simple guard implementation, which looks, as shown below.

  1. ---------  
  2. ---------  
  3. ---------  
  4. @NgModule({  
  5.   ---------  
  6.   ---------  
  7.   ---------  
  8.   providers: [canActivateGuard,   
  9.   useValue: () => {  
  10.   return true;  
  11.   }],  
  12.   ---------  
  13.   ---------  
  14.   ---------  
  15. })  
  16. export class AppModule { }  

If you observe the block of code given above, it is just a provider with some made up token, which resolves to a guard function that returns true. As this guard is always returning true, so it is not protecting anything, as it always activates the route that uses it.

Once a guard is registered with a token, we can use them in our route configuration. If you observe the block of code given below, the RouteGuard attached with the route configuration, which gets executed when we navigate to a specific route.

  1. import { Routes } from '@angular/router';  
  2. import { UserListComponent } from './components/user/user.list.component';  
  3. import { NewUserComponent } from './components/user/new.user.component'  
  4. import { TodoComponent } from './components/todo/todo.component';  
  5. import { UserComponent } from './components/user/user.component';  
  6. import { LoginComponent } from './components/login/login.component';  
  7. import { RouteGaurd } from './services/route.gaurd';  
  8. import { NewUserGaurd } from './components/user/new.user.gaurd';  
  9.   
  10. export const APP_ROUTES: Routes = [  
  11.   {  
  12.     path: '', component: LoginComponent  
  13.   },  
  14.   {  
  15.     path: 'login', component: LoginComponent  
  16.   },  
  17.   {  
  18.     path: 'users',  
  19.     canActivate: [RouteGaurd],  
  20.     children: [  
  21.       {  
  22.         path: 'new', component: NewUserComponent,  
  23.         canDeactivate:[NewUserGaurd]  
  24.       },  
  25.       {  
  26.         path: '', component: UserListComponent  
  27.       }  
  28.     ]  
  29.   },  
  30.   {  
  31.     path: 'user/:id', component: UserComponent, canActivate: [RouteGaurd]  
  32.   },  
  33.   {  
  34.     path: 'todos',  
  35.     component: TodoComponent , canActivate: [RouteGaurd]  
  36.   },  
  37.   {  
  38.     path: 'todos/:id', component: TodoComponent, canActivate: [RouteGaurd]  
  39.   }  
  40. ];  

We can have multiple guards to protect a single route. They execute in the order they are defined on the route.

Guards as Classes

Let's say our application needs to validate for an authenticated user before allowing to access the Application. Thus, to protect a route, we have to authenticate the user first. In such a case, guard class will be a perfect selection. To create a guard class, we should implement either CanActivate, CanActivateChild or CanDeactivate interfaces. Based on the interface implementation, we should define the respective methods canActivate(), canActivateChild(), canDeactivate(); they are equivalent as guard function. The block of code snippet given below shows you a simple CanActivate guard class implementation.

CanActivate Guard as a class

  1. import {Injectable} from '@angular/core';  
  2. import {CanActivate, Router} from '@angular/router'  
  3. import {AuthService} from '../services/auth.service'  
  4.   
  5. @Injectable()  
  6. export class RouteGaurd implements CanActivate{  
  7.     constructor(private _authService: AuthService, private route: Router){}  
  8.     canActivate(){  
  9.         console.log("Gaurd invoked")  
  10.         if(this._authService.isAuthenticated())  
  11.         {  
  12.             console.log("User found:"this._authService.getLoggedInUserData())  
  13.             return true;  
  14.         }  
  15.         console.log("Invalid user!");  
  16.         this.route.navigate(['/login']);  
  17.         return false;  
  18.     }  
  19. }  

Registering the above created guard class in app.module.ts file (AppModule class) as a provider.

  1. ---------  
  2. ---------  
  3. ---------  
  4. @NgModule({  
  5.   ---------  
  6.   ---------  
  7.   ---------  
  8.   providers: [AuthService, RouteGaurd]  
  9. })  
  10. export class AppModule { }  

Once we register in app.module.ts file (AppModule class) as a provider, then we can use them in a route.

  1. {  
  2.     path: 'todos',  
  3.     component: TodoComponent , canActivate: [RouteGaurd]  
  4.   },  

CanDeactivate Guard as a Class

We have seen the uses of CanActivate class. It is very simple. Before navigating a route, it validates first, followed by allowing it to navigate, whereas CanDeactivate works just a reverse way, before leaving the current route, it gives us an alert to decide, if we really want to navigate away from the current route. This is very useful, when we don't want to lose the filled form data, if accidently clicking on a Cancel button or some navigation buttons.

The implementation of CanDeactivate guard is almost similar as CanDeactivate guard implementation. The sample code snippet screenshot is given below.

  1. import { Injectable } from '@angular/core';  
  2. import { Routes } from '@angular/router';  
  3. import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router'  
  4. import {NewUserComponent} from './new.user.component';  
  5. import {Observable} from 'rxjs/rx';  
  6.   
  7. @Injectable()  
  8. export class NewUserGaurd implements CanDeactivate<NewUserComponent>{  
  9.     constructor(){}  
  10.     canDeactivate(component: NewUserComponent,  
  11.     router: ActivatedRouteSnapshot,  
  12.     state: RouterStateSnapshot):  
  13.     Observable<boolean> | Promise<boolean> | boolean{  
  14.         console.log("canDeactivate: ", component);  
  15.         if(!component.user.firstName){  
  16.             return confirm("Please fill the form!");  
  17.         }  
  18.         return true;  
  19.     }      
  20. }  
Angular 2

In the code snippet given above, there is one thing that we did not see in the previous code snippet. CanDeactivate<T> uses a generic, so we need to specify what component type; we want to deactivate. Here, honestly even I don't know why the syntax varies compared to CanActivate uses. I am not sure whether this is a bug or not but other than this, the rest of the things are the same as CanActivate syntax.

Registering the above created guard class in app.module.ts file (AppModule class) as a provider.

  1. ---------  
  2. ---------  
  3. ---------  
  4. @NgModule({  
  5.   ---------  
  6.   ---------  
  7.   ---------  
  8.   providers: [ConfirmDeactivateGuard]  
  9. })  
  10. export class AppModule { } 

Once we register in app.module.ts file (AppModule class) as a provider, then we can use them in a route.

  1. {  
  2.     path: 'users',  
  3.     canActivate: [RouteGaurd],  
  4.     children: [  
  5.       {  
  6.         path: 'new', component: NewUserComponent,  
  7.         canDeactivate:[NewUserGaurd]  
  8.       },  
  9.       {  
  10.         path: '', component: UserListComponent  
  11.       }  
  12.     ]  
  13.   },  

Output

Screenshot #1 is given below.

Angular 2

Screenshot #2 is given below.

Angular 2

Screenshot #3 is given below.

Angular 2

Conclusion

I love these features because they prompt us to protect from accidentally losing the data; and also, they are very useful to validate the user before they allow us to navigate a particular route. In addition to it, we can use multiple guards to protect a single route.

Happy coding!

Up Next
    Ebook Download
    View all
    Learn
    View all