DEV Community

seshubabubatchu
seshubabubatchu

Posted on

1 1

Angular Routing #4

Angular Route Guards

We use the Angular Guards to control, whether the user can navigate to or away from the current route.

Uses of Angular Route Guards

  • To Confirm the navigational operation
  • Asking whether to save before moving away from a view
  • Allow access to certain parts of the application to specific users
  • Validating the route parameters before navigating to the route
  • Fetching some data before you display the component.

Types of Route Guards

  • CanActivate - If a Route can be accessed or not?
  • CanDeactivate - If Current Route can be leaved or not?
  • Resolve - Load or perform some operations before entering Route
  • CanLoad - This guard works similar to CanActivate guard with one difference. The CanActivate guard prevents a particular route being accessed. The CanLoad prevents entire lazy loaded module from being downloaded, Hence protecting all the routes within that module.
  • CanActivateChild - This guard determines whether a child route can be activated. This guard is very similar to CanActivateGuard. We apply this guard to the parent route. The Angular invokes this guard whenever the user tries to navigate to any of its child route.

Implementing RouteGuards

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot,RouterStateSnapshot } from '@angular/router';

@Injectable()
`export class ProductGuardService implements CanActivate {

constructor(private _router:Router ) {

}

canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
console.log("canActivate"); //return true

//remove comments to return true

alert('You are not allowed to view this page. You are redirected to Home Page');
this._router.navigate(["home"]);

return false;

} }`

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay