The Angular router has 5 different route guards that can be used to control user navigation in the browser.
Such guards can be used in scenarios such as:
- Preventing users from navigating to parts of an application without authorization
- Preventing users from leaving a form before it is saved or completed
- Making sure the user is logged in before proceeding to the next page
A guard is a function (class-based guards are deprecated as of Angular 15.2) that can return three different values:
true
if we want to allow the user to proceed (then the navigation happens)false
if we want to prevent the user from proceeding (then the navigation doesn’t happen)- A
UrlTree
if we want to redirect the user to another component (usually a login component or an error component)
Sometimes, we want to ask a server about the user, which means that our guard is going to do asynchronous work. That’s fine because guards can return an Observable
or a Promise
of the above values, which means that a guard can return any of the six following types:
Any route can be protected by one or more guards. In the router config, we define an array of guards for each route as follows:
The above code means that in order to access the path /team/:id
, a user has to satisfy the requirement of canActivateTeam
, a guard function that returns one of the values documented above.