Route guards and resolvers

Intermediate · 24 min

Functional guards that control whether a navigation is allowed, and resolvers that fetch data before a route activates.

Before thisRoute parameters and query parametersDependency injection fundamentals and the injector tree

Code Shots With Profanis · 24 min

Route guards and resolvers

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Code Shots With ProfanisReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A guard is a function that returns (or resolves to) true, false, or a UrlTree — true allows navigation, false blocks it, and a UrlTree redirects somewhere else entirely.
  • CanActivate checks before entering a route; CanDeactivate checks before leaving one (the unsaved-changes-warning case); CanMatch controls whether a route is even considered a match in the first place.
  • A resolver fetches data before the route activates, so the component mounts with its data already available — no loading flicker between the component existing and its data arriving.

Not every navigation should be allowed

A route’s path matching whatever the user typed doesn’t mean the navigation should actually be allowed to happen — an unauthenticated user shouldn’t reach /admin, and a user with unsaved changes probably shouldn’t leave a form without at least being asked. Guards are the mechanism for intercepting a navigation and deciding, programmatically, whether it’s allowed to proceed.

CanActivate: gatekeeping entry to a route

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isLoggedIn() ? true : router.parseUrl('/login');
};
{ path: 'admin', component: AdminComponent, canActivate: [authGuard] }

A guard is just a function — the modern, functional style shown here, rather than a class implementing an interface the way guards worked in older Angular. It returns (or can return a Promise/Observable resolving to) one of three things: true allows the navigation, false blocks it outright, and a UrlTree (built with router.parseUrl(...) or router.createUrlTree(...)) redirects elsewhere entirely. That third option matters in practice far more than it might look — a blocked navigation with no redirect just leaves a user stuck, while a redirect actually sends them somewhere useful, like a login page.

CanMatch is a related but distinct guard, worth knowing exists: it runs before the router even commits to a route being a match at all, which matters for cases like serving entirely different components at the same path depending on a condition. CanDeactivate runs the opposite direction — before leaving a route — and is the standard mechanism behind “you have unsaved changes, are you sure?” confirmation prompts.

Resolvers: fetching data before the component exists

export const userResolver: ResolveFn<User> = (route) => {
  const userService = inject(UserService);
  return userService.getUser(route.paramMap.get('id')!);
};
{ path: 'users/:id', component: UserDetailComponent, resolve: { user: userResolver } }
// inside UserDetailComponent
private route = inject(ActivatedRoute);
user = this.route.snapshot.data['user']; // already resolved, no fetch needed here

A resolver runs before the route finishes activating, fetching whatever data the route needs ahead of time. By the time UserDetailComponent actually mounts, route.snapshot.data['user'] already holds the resolved value — there’s no gap where the component exists but its data hasn’t arrived yet, which is exactly the gap that would otherwise need its own loading-state handling inside the component. The tradeoff is the mirror image: the navigation itself doesn’t complete until the resolver’s data arrives, so a slow resolver delays the whole page transition rather than letting the component render immediately and show its own loading indicator.

Combining several guards on one route

A route isn’t limited to one guard — canActivate takes an array, and every guard listed has to return true for the navigation to proceed:

{ path: 'admin', component: AdminComponent, canActivate: [authGuard, adminRoleGuard] }

Each guard stays focused on one concern — authGuard checks that someone’s logged in at all, adminRoleGuard separately checks they have the right role — rather than one bloated guard trying to express every reason a navigation might be disallowed. This composability mirrors the same instinct behind keeping HTTP interceptors small and single-purpose, from a few lessons back: small, independently testable functions, combined declaratively at the route level, rather than one large function doing everything at once.

This lesson’s video is the one with the clearest coverage of functional guards specifically; the two linked videos cover the resolver half directly, since no single video found during this roadmap’s research covered guards and resolvers together at the depth both deserve.

Check yourself

  1. 01A functional guard returns `inject(Router).parseUrl('/login')` instead of `false` when a user isn't authenticated. What's the practical difference from just returning `false`?

    Returning `false` blocks the navigation and leaves the user wherever they already were, with no further action. Returning a `UrlTree` (what `parseUrl()` produces) tells the router to redirect to that URL instead — the user ends up on the login page rather than stuck on whatever page they tried to leave, which is almost always the behavior you actually want for an auth guard.

  2. 02Why would a route use a resolver to fetch its data, instead of just having the component fetch its own data in ngOnInit?

    A resolver runs before the route activates, so by the time the component is constructed and rendered, the data is already available — no loading spinner needed inside that component just to cover the gap between mounting and data arriving. Fetching in `ngOnInit` instead means the component exists and renders first, then shows a loading state until the fetch resolves — a resolver moves that wait earlier, before navigation completes at all.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark