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 },
]
CanActivateFn(from@angular/router) is the type for a guard written as a function that is asked before entering. This guard receives two parameters:route, which holds details of the target route, andstate.state.urlholds the target address, here'/orders'.- This guard is a function, not a class, so it has no constructor. Services come from
inject(). That's allowed because the router runs guards inside an injection context. canActivate: [authGuard]puts the guard on the route. It's an array, so there can be more than one guard. When there are several, all of them must allow.
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 |
router.createUrlTree(['/login'], { queryParams: { returnTo: state.url } })also makes a UrlTree. The difference: the address gets the query parameter?returnTo=%2Forders(%2Fis/), so the login page knows where to go back to.router.navigate(['/login'])followed byreturn falsealso gets there, but that's two steps. A UrlTree takes one step.- A guard may also return an Observable or a Promise that holds one of those answers. The router waits for the answer.
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] },
CanDeactivateFn<OrdersPage>receives the component on screen as its first parameter (page), so the guard can read what's in it, here thenoteproperty.- If the note is empty, the customer may leave. If it's filled in,
confirm()(the browser's built-in dialog with OK and Cancel buttons) asks first. If Cancel is clicked, the guard returnsfalse. - The router asks the route being left first (
canDeactivate), then the target route (canActivate). - The Playground turns dialogs off, so
confirm()is alwaysfalsethere: with the note"Spicy", the console writesunsentGuard runs, note: "Spicy"and you stay on Orders.
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 |
resolve: { menu: menuResolver }runs the resolver and stores its result under the namemenu.- The router waits for the Observable from
getMenu()to finish, then creates MenuPage. So a resolver loads data before the navigation finishes, and the component gets ready data straight fromsnapshot.data['menu']. - While it waits, the old page stays. When the app has just opened,
<router-outlet>is empty until the data arrives. - If the request fails, the navigation is cancelled and the old page stays. The console writes the error, for example
ERROR Error: Http failure response: 500.
📌 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
return falsewith no redirect. The customer is stuck with no explanation. Returnrouter.parseUrl('/login').- Thinking
canActivatealso guards the way out. A guard incanActivateis only asked before entering. A form that hasn't been sent needscanDeactivate. - Thinking a guard protects the data. A guard only runs in the customer's browser. Anyone can change
loggedInin DevTools. They can also send a request straight to the orders API (the address on the server that takes orders) withcurl(a command-line program), without going through the router at all. A guard only decides which page is shown. The server must still check the token (proof that the customer has logged in) on every request, and refuse with status 401 when there is no token. inject()inside a callback. Callinject()in the first lines of the guard function, not inside asubscribeorsetTimeoutthat runs later. When that callback runs, the injection context is gone.- Exercise details. The guard is
export const authGuard: CanActivateFn = (route, state) => { ... }, withinjectfrom@angular/coreandCanActivateFn, Routerfrom@angular/router. Inside:const router = inject(Router), thenif (isLoggedIn) return trueandreturn router.parseUrl('/login'). The grader looks for the textreturn true,=> trueor? true :, soreturn isLoggedIn ? true : router.parseUrl('/login')is accepted too.
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.