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
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
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
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; } }
@NgModule({ … providers:[ ... ConfirmDeactivateGuard ] }) export class AppModule {}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.