In your Angular application you may need to control access to different parts of your app. To control that kind of authorization and authentication you can use route guards in Angular.
Using route guards, you can perform some action before navigating to another route and you can restrict access to routes based on the outcome of that action. In this post we’ll see example of using CanActivate route guard to restrict access to route based on whether user is authenticated or not.
Why route guards in Angular
Use of route guards to control access in your Angular app may be considered for following scenarios-
- User is not authorized to navigate to the component rendered by the route user want to navigate to.
- User is not authenticated (not logged in).
- You need to fetch some data before you display the target component.
- You want to save pending changes before leaving a component.
- You want to ask the user if it's OK to discard pending changes rather than save them.