Skip to the page

Forms, routing and HTTP · mid

Functional guards, resolvers and lazy-loaded routes

Functional guards decide if a route may open. canMatch stops the lazy code from loading at all. Lazy routes split the bundle.

The notes

What you must know

  • A guard is a function, for example CanActivateFn: it uses inject() and returns a boolean, a UrlTree, a RedirectCommand, or an Observable or Promise of those.
  • Redirect with inject(Router).createUrlTree(["/login"], { queryParams: { returnUrl: state.url } }).
  • canMatch decides whether a route matches at all. On a lazy route it stops the chunk from downloading.
  • Checking the role inside the admin component after /api/me returns loads the lazy code first and flashes, then redirects. Use canMatch: [roleGuard("admin")] on the route.
  • A client-side guard is not security. The API must check permissions again.
  • Lazy routes: loadComponent: () => import("./reports/reports").then(m => m.Reports) or loadChildren.
  • The build turns each dynamic import into a separate chunk. Preloading downloads chunks early when the browser is idle.

The red pen

Common traps: mistake → fix

  • Mistake: A route guard protects the data

    Fix: only the server protects data.

  • Mistake: canActivate and canMatch are the same

    Fix: canMatch also decides lazy loading.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you write a functional guard?
  2. How do you stop non-admin users from loading the admin code?
  3. How do you lazy-load a route?
  4. What is the difference between canActivate and canMatch?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview