Route Guards
Creating route guards in Angular
In Angular routing, the user navigates from one view to another using routes. These route paths are configured inside the routing modules and make it accessible to the user to access one route from another as per the code. However, in real-case scenarios, we have so many requirements where we would not want a user to access all the possible route paths inside our application.
Let’s take one example.
Suppose the user is filling out a long application form and midway wants to check some details regarding the form by going back to the intro information. However, if they do that, they will lose the details they have entered in the form. In this case, the application needs to put a guard where it informs the user wanting to go back that you will lose the information entered on this page if you navigate back to another view. “Are you sure you want to leave this page?”, sounds familiar, doesn’t it? This is one good example to understand the use cases of route guards. Route guards not only help us secure the application, but are also useful in monitoring, authorizing, or preventing the user from leaving the route.
Type of route guards
The different route guards provided by Angular are all used for several purposes like monitoring, securing, etc. Let’s look at some of those:
• canActivate
• canActivateChild
• canDeactivate
• canLoad
• resolve
The canActivate
route guard is used to guard the navigation to a route whereas, the canActivateChild
route guard will secure the navigation from one route to a child route. canDeactivate
route guard, on the other hand, will guard the navigation away from the route that is preventing the user from leaving a route. These three are the most commonly used routed guards. However, two more types of route guards are used for routing purposes.
canLoad
guard is used when the user wants to lazy load routes. It comes in handy when preventing asynchronous routing. The resolve route guard is another type of guard which as the name suggests, is used when you want to resolve something before anything appears on the view. We will learn about Route resolvers in a later lesson. When the user needs to pre-fetch some data before loading the next route component template view, resolve route guards are used.
Let’s now look at the order of execution of these route guards in an Angular application. The implementation of these route guards in a particular order is very important because, at every step, the user must be able to access the route with a secure and monitored route activity. The order goes as follows:
Get hands-on with 1400+ tech skills courses.