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;

} }`

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay