NG.V · Angular 22 practice question

When implementing a functional `canActivate` guard in Angular, which pattern represents the most robust and idiomatic approach to ensure navigation is blocked if authentication fails, assuming the guard needs to return a boolean, an Observable that resolves to a boolean, or a UrlTree? Avoid this incorrect class-style pattern, which returns `true` before the async auth check completes:

canActivate(): boolean {
  this.authService.isLoggedIn().then(isLoggedIn => {
    if (!isLoggedIn) this.router.navigate(['/login']);
  });
  return true;
}
Choose one answer
Check answer and explanation

Correct answer: Return an Observable that emits `true` if the user is logged in, and `false` otherwise (or a `UrlTree` for redirection).

Explanation

The functional guards in modern Angular routing are designed to return an observable or a boolean. Returning an observable is the preferred pattern because it allows the guard logic (e.g., asynchronous API calls to check auth status) to complete naturally, and the router waits for the observable to resolve before proceeding. If redirection is needed, returning a `UrlTree` inside the observable is the cleanest way to handle it.

Common trap

Developers often default to the synchronous boolean return type, leading them to incorrectly return `true` immediately in the face of asynchronous checks, which bypasses the guard logic entirely.

Source: Angular Router Guide - Router Guards (Conceptual check based on standard RxJS/Angular best practices for guards) https://angular.dev/guide/routing/common-router-tasks
Checked against the cited text on 2026-11-27.

Report an error in this question