Route Guards - sravanthimendu98/angular GitHub Wiki

https://raghuvardhankaranam.medium.com/route-guards-in-angular-c2c01fe6167b#:~:text=One%20of%20the%20ways%20Angular,then%20you've%20encountered%20guards.

In Angular, a guard is a script that runs before certain stages of route navigation. It decides whether to proceed with the navigation or redirect it.

Types of guards:

  • CanActivate
  • CanActivateChild
  • CanDeactivate
  • Resolve
  • CanLoad
  • CanMatch

Command to create Guard: $ ng generate guard auth

CanActivate The CanActivate guard checks whether a route can be activated. This is useful for protecting routes that should not be accessible unless certain conditions are met, like user authentication.

image image

CanActivateChild

Similar to CanActivate, but it works on child routes. Useful for feature modules with multiple child routes.

image

CanDeactivate

This guard works when we are navigating away from a component. It is often used to warn the user about unsaved changes.

image

Resolve

A Resolve guard fetches data before navigation completes. The data can be used to populate route parameters.

CanLoad

CanLoad checks if a module should be lazy-loaded or not. This is important if you want to prevent unauthorized users from downloading parts of your application.

CanMatch checks with the url pattern.