Sub topic 1
Angular Route Guards and Resolvers: How Navigation Works
Prerequisites
This chapter assumes basic TypeScript, Angular components and services, Angular routing, dependency injection, and familiarity with RxJS Observables and Promises.
How the Router Navigates
When a URL changes, the Angular router matches it against the Routes configuration. It then checks whether the navigation may continue, loads required data, and activates the component in router-outlet.
What Guards and Resolvers Are For
A route guard is a function that decides whether navigation can continue. Use guards for conditions such as authentication, permissions, or unsaved form changes.
A resolver is a function that loads data before the routed component activates. This lets the component receive required data when it starts. Both can perform asynchronous work, so navigation can pause while they finish.
| Feature | Main question | Typical use |
|---|---|---|
| Guard | May the router continue? | Authentication |
| Resolver | What data does the component need? | Load a product |
> callout note > Guards improve navigation behavior, but they are not a security boundary. The server must enforce authorization for every protected operation.
Writing Functional Guards with `inject()`
A functional guard is a function typed with a router guard type. Use inject() inside the function to access Angular services without defining a guard class.
What a Guard Can Return
A guard can return:
trueto allow navigation.falseto cancel navigation.- A
UrlTreeto redirect to another URL. - A synchronous value, Promise, or Observable containing one of these results.
Avoid calling router.navigate() inside a guard. Returning a UrlTree lets the router manage the redirect as part of the current navigation.
Protecting a Route with `canActivate`
canActivate runs before the route's component activates:
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);
return auth.isLoggedIn()
? true
: router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};Attach it to a route with canActivate: [authGuard]. An anonymous user is redirected to login, while the requested URL is preserved for return navigation.
Exercise
What should a guard return when an anonymous user tries to open /admin and should go to /login?
Show answer
Return a UrlTree, such as router.createUrlTree(['/login']).