Protecting routes using guards in angular2

Posted By : Manisha Kirodiwal | 29-Oct-2017

Protecting routes using guards in angular2 Protecting routes is very necessary when we want to block users from accessing routes that they are not allowed to access. Angular router proivdes Navigation Guards to solve this problem.

Guard Types:

  • CanActivate: It decides that if route can be activated
  • CanActivateChild: It decides that if children routes of a route can be activated
  • CanDeactivate:It decides that if route can be deactivated
  • CanLoads:It decides that if children routes route can be deactivated

How to define Guards:

As function:

To register a guard define a token and a guard function:

@NgModule({
…
providers:[
provide: ‘CanAlwaysActivateRoute’
useValue: () =>{
Return true;
}
],
…
})
export class AppModule {}

Its a provider with token that resolves a guard function that returns true always means not protecting anything. After guard registration use it in route configuration.

export const AppRoutes:RouterConfig=[
{
path: ‘’,
component: somecomponent,
canActivate: [ ‘CanAlwaysActivateRoute’]
}];

We can have multiple guards protecting a single route also.

As Classes:

When guard needs dependency injection capabilities then we define a guard as a class.

Following code shows CanActivate guard implementation as classes:

import {Injectable} from ‘@angular/core’;
import {CanActivate} from ‘@angular/router’;
import {AuthService} from ‘@.auth.service’;

@Injectable()
export class CanActivateViaAuthGuard implements CanActivate {
constructor(private authSerivce: AuthService) {}

canActivate(){
return this.authService.isLoggedIn();
}
}

Now register this guard as a provider:

@NgModule({
…
providers:[
authService,
CanActivateViaAuthGuard
]
})
export class AppModule {}

Now we can use it on a route:

{ 
path: ‘’,
Component: somecomponent,
canActivate: [
‘canAlwayActivateGuard’,CanActivateViaAuthRoute
]
}

DeActivating Routes:

We have to create a function or a class similar to the canActivate guards that implements the CanDeactivate interface:

import { canDeactivate } from ‘@angular/router’;
import { canDeactivateComponent } from ‘@.app/can-deactivate’;

export class ConfirmDeactivateGuard implements CanDeactivate {

canDeactivate(target: canDeactivateComponent){
 if(target.hasChanges()){
   return window.confirm(‘Do you really want to cancel?’);
}
return true;
}
}

canDeactivate() function called by the angular’s router if needed. Now register the guard accordingly:

@NgModule({
…
providers:[
...
ConfirmDeactivateGuard
]
})
export class AppModule {}

About Author

Author Image
Manisha Kirodiwal

Manisha is a Web Application developer and she is good in working with Angular, TypeScript , JavaScript and Jquery. In free time she loves to dance and cooking.

Request for Proposal

Name is required

Comment is required

Sending message..