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 Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up