How would you protect a component being activated through the router?

Technology CommunityCategory: AngularHow would you protect a component being activated through the router?
VietMX Staff asked 3 years ago

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() or canActivateChild() 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 access
  • CanActivateChild: Check if a user has access to any of the child routes
  • CanDeactivate: Can a user leave a page? For example, they haven’t finished editing a post
  • Resolve: Grab data before the route is instantiated
  • CanLoad: Check to see if we can load the routes assets