Route Guards

Learn how to pass and retrieve complex data structures through route guards with the help of an example Ionic app.

The second way we can handle passing and retrieving more complex data structures through navigation routes is with route guards.

Guarding routes

The underlying Angular framework allows developers to instruct the router on the conditions under which access to a particular route is permitted or denied.

This is very helpful in certain use cases, such as only granting authorized users access to secure areas of an application or providing different content to users based on their permission roles.

Route guards make such functionality possible through the following interfaces:

  • The CanActivate interface manages navigation to a route.
  • The CanActivateChild interface manages navigation to a child route.
  • The CanDeactivate interface manages navigation away from the current route.
  • The CanLoad interface manages navigation to an asynchronously loaded feature module.
  • The Resolve interface manages retrieval of route data before the route is activated.

We’ll explore the CanActivate and resolve route guards to only allow access to specific routes within an application that we’ll develop over the following pages.

This application will allow or disallow access based on a specific string being passed as a route parameter. It’s important to note that the code we’ll cover handles this admittedly “silly” authentication example, but demonstrates how we can use route guards to manage access to specific areas of the application.

With that disclaimer out of the way, let’s start!

Creating a new app

We create a new Ionic project using the following command:

ionic start ionic-navigation blank --type=angular

Once the ionic-navigation project has been successfully created, we need to change into the root directory of the project and create the following services and page components:

  • The DetailsPage holds the component that we want to navigate to.
  • The DetailsGuardService is an Angular service that we’ll use to determine whether the declared route is accessible or not.
  • The DetailsResolverService is an Angular service that retrieves and supplies data from a remote URL to the active route.
cd ./ionic-navigation
ionic g page pages/details
ionic g service resolvers/details-resolver
ionic g service guards/details-guard

You can try running these commands in the Terminal provided below!

Get hands-on with 1200+ tech skills courses.