Check out our Angular Book Series.

What are Route Guards in Angular?

When you build an Angular application, you're probably going to use a router. The router is a library that allows you to change the URL of the application, and with that URL change to load new components. How do you protect parts of your application from being accessed by users who are not authorized? You use a Route Guard.

What is a Route Guard?

A Route Guard is code that Angular will execute when processing the route. I have been using one to determine whether a user should have access to the route or not. However, they can be used for any purpose. There are a handful of different hooks that can be used:

  • CanActivate to mediate navigation to a route. This is the one I'll demonstrate today.
  • CanActivateChild to mediate navigation to a child route.
  • CanDeactivate to mediate navigation away from the current route.
  • Resolve to perform route data retrieval before route activation.
  • CanLoad to mediate navigation to a feature module loaded asynchronously.

That list is copied from the documentation, because I don't think a lot of elaboration is needed.

Using CanActivate

I'm going to use modified code from my latest book on Angular 6, which you should get if you want a beginner's introduction to Angular.

The first step is to create a Service:


import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
constructor() {}
canActivate() {
return userHasLoggedIn
}
}

The guard is marked as Injectable and implements the CanActivate method. I greatly simplified the algorithm for determining whether a user has logged in or not, but it can be as complex as you need it. I'm just returning a Boolean value. If the user has logged in--via the userHasLoggedIn value, then the user can activate this route and the canActviate() method returns true. If the user has not logged in, then canActivate() returns false and Angular will know now to load the route.

Since this is a service, load it in your module. In the LearnWith books, I set up a module strictly for routing purposes, so it looks something like this:


import {AuthGuard} from "./auth-guard.service";
@NgModule({
imports: [ RouterModule.forRoot(ROUTES) ],
exports: [ RouterModule ],
providers: [AuthGuard],
})

A constant named ROUTES defines the application's roots:


const ROUTES : Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'GotIn', component: MainApplicationComponent, canActivate: [AuthGuard] },
];

The object which defines the router has a canActivate property and uses the AuthGuard class as it's value. So, when the user purposely tries to load the GotIn route, the canActivate() method inside the AuthGuard class will execute and determine whether the user can view this route based on their logged in status.

Route Guards a powerful and something to learn if you care about the security if your application.

Be sure to pick up my full book series on Angular 6.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.