Sub topic 4
What a guard can return
Prerequisites and scope
This chapter assumes you can write a functional guard with inject() and you know how Observables and Promises differ. It covers what the router does with the value your guard produces. That value decides whether the navigation continues, stops, or goes somewhere else.
The return type
Every functional guard (CanActivateFn, CanActivateChildFn, CanDeactivateFn, CanMatchFn) returns a MaybeAsync<GuardResult>. Expanded, that is:
- A
GuardResult, which isboolean | UrlTree | RedirectCommand. - Or an
Observableof aGuardResult. - Or a
Promiseof aGuardResult.
RedirectCommand exists from Angular 18. In older versions, the result is boolean | UrlTree.
| Value | Effect on the navigation |
|---|---|
| `true` | The guard passes. The router continues with the next guard or step. |
| `false` | The navigation is cancelled. The router stays on the current URL. |
| `UrlTree` | The current navigation is cancelled and a new navigation to that URL starts. |
| `RedirectCommand` | Same as a `UrlTree`, but you can also pass navigation options for the redirect. |
| Observable or Promise | The router waits, then treats the value it produces as one of the rows above. |
Boolean results
Returning true lets the navigation proceed. Returning false cancels it without telling the user anything. The browser URL does not change, and the user stays where they were.
Be careful with false on a first load. If a user pastes a deep link and a canActivate guard returns false, there is no previous page to stay on. The router outlet stays empty. For protected routes, return a UrlTree instead, so the user lands somewhere useful.
import { CanActivateFn } from '@angular/router';
// Synchronous: the router continues immediately.
export const alwaysOpen: CanActivateFn = () => true;
// Synchronous: the navigation is cancelled and nothing is shown to the user.
export const alwaysClosed: CanActivateFn = () => false;UrlTree results
A UrlTree is the router's parsed representation of a URL. You build one with router.createUrlTree() or router.parseUrl(). When a guard returns it, the router drops the current navigation and starts a new one to that URL. The new navigation runs its own guards, so a redirect target that is also guarded can trigger a further redirect.
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);
if (auth.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};Returning a UrlTree is better than calling router.navigate() inside the guard and then returning false. The UrlTree keeps the redirect inside the single navigation pipeline, so the router can order, cancel, and report it correctly. A manual navigate() call starts a second, competing navigation.
RedirectCommand
RedirectCommand wraps a UrlTree and adds NavigationBehaviorOptions. Use it when the redirect needs settings such as replaceUrl, which replaces the history entry so that the Back button does not return to the blocked URL.
import { inject } from '@angular/core';
import { CanActivateFn, RedirectCommand, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authRedirectGuard: CanActivateFn = () => {
const router = inject(Router);
if (inject(AuthService).isLoggedIn()) {
return true;
}
return new RedirectCommand(router.parseUrl('/login'), { replaceUrl: true });
};A plain UrlTree is enough in most cases. Reach for RedirectCommand only when you need those options.
Asynchronous results
Guards often depend on something slow, such as a session check against a server. Return an Observable or a Promise and the router waits for it. The router uses the first value the Observable emits, so a long-lived stream does not block it. Always make sure the stream emits at least once.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { catchError, map, of } from 'rxjs';
import { AuthService } from './auth.service';
// Assumes AuthService.checkSession(): Observable<boolean>
export const sessionGuard: CanActivateFn = () => {
const router = inject(Router);
return inject(AuthService)
.checkSession()
.pipe(
map((valid) => (valid ? true : router.parseUrl('/login'))),
catchError(() => of(router.parseUrl('/login'))),
);
};The same guard written with a Promise and async/await:
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { AuthService } from './auth.service';
export const sessionGuardAsync: CanActivateFn = async () => {
const router = inject(Router);
try {
const valid = await firstValueFrom(inject(AuthService).checkSession());
return valid ? true : router.parseUrl('/login');
} catch {
return router.parseUrl('/login');
}
};There is one trap here. inject() works only in the injection context, which is the synchronous part of the guard before the first await. In the example above, both inject() calls happen before any await. If you call inject() after an await, it throws. Collect every dependency at the top of the function.
Errors
A guard that throws, or whose Observable errors, does not count as false. The navigation fails with an error. The router rejects the promise from router.navigate() and emits a NavigationError event. Unless you configured an error handler, the user sees nothing useful.
Decide what failure means for each guard. For an authentication check, "could not verify" usually means "not allowed", so catch the error and return a redirect, as sessionGuard does. For an optional enhancement, you might let the user through on failure. Make that choice in the code with catchError.
How the router picks an outcome
Several guards on one route
When a route lists several guards, such as canActivate: [authGuard, roleGuard], the router runs them and combines the results. All must return true for the navigation to continue. If one returns a UrlTree, the router redirects to it. If several return different redirects, the first one wins, in the order the guards are listed. Keep the cheap, synchronous checks first so you avoid a server call when the answer is already known.
Summary of rules
- Return
trueto allow, aUrlTreeto redirect, andfalseonly when staying put is the right result. - Prefer returning a redirect over calling
router.navigate()inside a guard. - For async work, return an Observable or Promise that always produces a value.
- Call
inject()before anyawait. - Handle errors yourself so a failed request does not become an unhandled navigation error.
Exercise
A canActivate guard calls inject(Router) after await firstValueFrom(...), and the app throws an error when the guard runs. What is wrong, and what should the guard return for a user who is not allowed in?
Show answer
inject() only works in the injection context, which ends at the first await. Move both inject() calls to the top of the guard, before any await. For a user who is not allowed in, return a UrlTree (for example router.parseUrl('/login')) rather than false, so a user who arrives by deep link ends up on a useful page instead of an empty outlet.
Exercise
Your guard returns of(true) when the request succeeds, but the request sometimes fails with an HTTP error and the user sees a failed navigation. How do you fix it so that failure sends the user to /login?
Show answer
Add catchError(() => of(router.parseUrl('/login'))) to the Observable pipeline. A thrown error or an errored Observable is a navigation error, not false. Catching it and returning a UrlTree makes the failure an explicit redirect.