The Angular router ships with a feature called guards. These provide us with ways to control the flow of our application. We can stop a user from visitng certain routes, stop a user from leaving routes, and more. The overall process for protecting Angular routes:
- Create a guard service:
ng g guard auth
- Create
canActivate()
orcanActivateChild()
methods - Use the guard when defining routes
// import the newly created AuthGuard
const routes: Routes = [
{
path: 'account',
canActivate: [AuthGuard]
}
];
Some other available guards:
CanActivate
: Check if a user has accessCanActivateChild
: Check if a user has access to any of the child routesCanDeactivate
: Can a user leave a page? For example, they haven’t finished editing a postResolve
: Grab data before the route is instantiatedCanLoad
: Check to see if we can load the routes assets