Guards and Resolvers — Angular

A guard is a function that answers "may I pass?" for a route. A CanActivateFn guard is asked before entering (canActivate: [authGuard]) and gets services with…

The Orders page is only useful to a customer who has logged in to their account. If someone opens /orders straight from a bookmark without logging in, the router still shows the page.

A guard adds one question before the page shows. A guard is a function the router asks before entering a route, or before leaving it: "may I pass?". Its partner, the resolver, is a function that prepares a route's data before its page shows. Picture Jali's stall with a kitchen at the back. At its door stands a guard. The guard checks your staff card before you go in (canActivate), and stops you on the way out if the order in your hands hasn't been sent (canDeactivate). Meanwhile a waiter puts the menu board on your table before you sit down (resolve). The kitchen is a route, the guard at the door is an Angular guard, and the waiter is a resolver.

CanActivateFn: a guard before entering

AuthService keeps the customer's logged-in state in the loggedIn signal, and authGuard reads that state:

// src/app/auth.service.ts
@Injectable({ providedIn: 'root' })
export class AuthService {
  loggedIn = signal(false)
}

// src/app/auth.guard.ts
import { inject } from '@angular/core'
import { CanActivateFn, Router } from '@angular/router'
import { AuthService } from './auth.service'

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService)
  const router = inject(Router)
  console.log('authGuard runs, heading to ' + state.url)

  if (auth.loggedIn()) return true
  return router.parseUrl('/login')
}

Then the guard is put on the Orders route:

// src/app/app.routes.ts
export const routes: Routes = [
  { path: '', redirectTo: 'menu', pathMatch: 'full' },
  { path: 'menu', component: MenuPage },
  { path: 'orders', component: OrdersPage, canActivate: [authGuard] },
  { path: 'login', component: LoginPage },
]

true, false or UrlTree

A guard can answer true, false or a UrlTree, which is a target address in a form the router understands. router.parseUrl('/login') makes a UrlTree from the text '/login'.

The guard returns What happens
true the navigation goes on, OrdersPage shows
false the navigation is cancelled: address and page stay, with no message and no error
router.parseUrl('/login') a UrlTree: the router cancels /orders and goes to /login instead

So with return false, clicking Orders does nothing: the customer stays on Menu and doesn't know why. Return a UrlTree so they're sent to the login page.

This is the Playground console when a customer who isn't logged in clicks Orders, then the Log in button:

Event Console Page
Click Orders authGuard runs, heading to /orders Log in first (/login)
Click Log in: loggedIn.set(true), then router.navigateByUrl('/orders') authGuard runs, heading to /orders Orders

CanDeactivateFn: a guard before leaving

This guard is put on the Orders route with canDeactivate, and it's asked when the customer is about to leave that page:

// src/app/unsent.guard.ts
export const unsentGuard: CanDeactivateFn<OrdersPage> = (page) => {
  console.log('unsentGuard runs, note: ' + JSON.stringify(page.note))
  return page.note === '' || confirm('Your order has not been sent. Leave anyway?')
}

// in the route list
{ path: 'orders', component: OrdersPage, canActivate: [authGuard], canDeactivate: [unsentGuard] },

ResolveFn: data ready before the page shows

This resolver gets the menu list through the MenuApi service, and the Menu route uses it through resolve:

// src/app/menu.resolver.ts
export const menuResolver: ResolveFn<Menu[]> = () => {
  console.log('menuResolver runs')
  return inject(MenuApi).getMenu()
}

// in the route list
{ path: 'menu', component: MenuPage, resolve: { menu: menuResolver } },

MenuPage reads the result from ActivatedRoute:

// src/app/menu/menu.ts
export class MenuPage {
  menu: Menu[] = inject(ActivatedRoute).snapshot.data['menu']

  constructor() {
    console.log('MenuPage created, menu: ' + this.menu.length)
  }
}

This is what happens when the customer moves from Orders to Menu:

Time Console What shows
Click Menu from Orders menuResolver runs still Orders
600 ms later, the data arrives MenuPage created, menu: 3 Menu with 3 pancakes

📌 When a resolver, when the component

A resolver makes the customer wait with no sign at all. For data that's quick and required (one menu item's details), a resolver fits. For slow data, fetch it in the component as in the HTTP Client lesson, and show "Loading...". The old form of a guard, a class with implements CanActivate, is still common in older projects. The function form above is the one used today. There is also canMatch. If canMatch returns false, the router doesn't cancel the navigation, but tries the next route whose path matches. This suits a feature flag, a switch in the code that turns a feature on or off. For example, two dashboard routes, one for the old view and one for the new view.

⚠️ Guards that stay silent, or stand at the wrong door

TL;DR: A guard is a function that answers "may I pass?" for a route. A CanActivateFn guard is asked before entering (canActivate: [authGuard]) and gets services with inject(). It returns true to go on, false to cancel with no message, or a UrlTree such as router.parseUrl('/login') to redirect to another address. A CanDeactivateFn<OrdersPage> guard is asked before leaving, receives the component on screen, and suits a form that hasn't been sent. A resolver prepares data: a ResolveFn in resolve: { menu: menuResolver } loads data before the navigation finishes. So the component is created with its data ready, and the old page stays while it waits. A guard only runs in the browser, so the server must still check permission on every request.

⚡ canActivate: a guard before entering

Write:

export const authGuard: CanActivateFn = (route, state) => {
  const auth = inject(AuthService)
  const router = inject(Router)
  if (auth.loggedIn()) return true
  return router.parseUrl('/login')
}
// { path: 'orders', component: OrdersPage, canActivate: [authGuard] }

Meaning: A guard is a function the router asks before entering a route: "may I pass?". The router asks the guards in canActivate before it opens /orders. If auth.loggedIn() is true (the customer has logged in), the guard returns true and the page shows. If not, the guard redirects to /login. A guard written as a function has no constructor, so services come from inject() in its first lines.

In the exercise, return true when isLoggedIn is true, and router.parseUrl('/login') otherwise.

⚡ false stays silent, a UrlTree redirects

Guess first: the guard on the Orders route only does return false. A customer who isn't logged in clicks Orders on the Menu page. What happens?

Nothing. The navigation is cancelled, the address and the page stay on Menu, with no message and no error. The customer doesn't know why.

Meaning: Return a UrlTree, a target address in a form the router understands, such as router.parseUrl('/login'). The router then cancels /orders and goes straight to the login page.

⚡ resolve: data ready before the page shows

Write:

{ path: 'menu', component: MenuPage, resolve: { menu: menuResolver } },

Meaning: menuResolver is a resolver: a function that prepares a route's data before its page shows. The router waits for the resolver's data, then creates MenuPage, so the component gets its data straight from snapshot.data['menu']. While it waits, the old page stays. For a guard that is asked on the way out, for example from a form that hasn't been sent, use canDeactivate.

What you will learn