[Angular] RoleGuard: redirect with RedirectCommand/UrlTree instead of router.navigate + return false; drop console.log noise #1168

Open
opened 2026-10-02 04:44:19 +00:00 by spikerj · 0 comments
Owner

Why

projects/spikersoft/src/app/_guards/role.guard.ts denies access by calling router.navigate(["/"]) and then returning false (two places, ~L24 and ~L36). That starts a second navigation from inside a running one (race-prone, and the original navigation is reported as cancelled rather than redirected). The router's supported way is to return a RedirectCommand (or UrlTree); Angular 22.2 additionally lets guards throw a RedirectCommand.

The guard also console.logs the user's realm roles and the grant/deny result on every guarded navigation.

What changes for us

  • Return type → Promise<boolean | RedirectCommand>; replace both navigate + false with return new RedirectCommand(router.parseUrl("/")) (consider skipLocationChange/replaceUrl so Back doesn't bounce).
  • Remove the three console.log lines (or route through the logging service at debug level).
  • Update role.guard specs (assert the returned redirect instead of a navigate spy).

Acceptance criteria

  • no router.navigate inside the guard; specs cover unauthenticated, missing role, granted
  • no role data logged to the console

Size: S. Returning RedirectCommand works today; the throw variant needs Angular 22.2.

Links: Throw variant needs #1165.


Filed from the 2026-10-02 spikersoft-angular pnpm outdated changelog review.

## Why `projects/spikersoft/src/app/_guards/role.guard.ts` denies access by calling `router.navigate(["/"])` and then returning `false` (two places, ~L24 and ~L36). That starts a second navigation from inside a running one (race-prone, and the original navigation is reported as cancelled rather than redirected). The router's supported way is to **return a `RedirectCommand`** (or `UrlTree`); Angular **22.2** additionally lets guards **throw** a `RedirectCommand`. The guard also `console.log`s the user's realm roles and the grant/deny result on every guarded navigation. ## What changes for us - Return type → `Promise<boolean | RedirectCommand>`; replace both `navigate + false` with `return new RedirectCommand(router.parseUrl("/"))` (consider `skipLocationChange`/`replaceUrl` so Back doesn't bounce). - Remove the three `console.log` lines (or route through the logging service at debug level). - Update `role.guard` specs (assert the returned redirect instead of a `navigate` spy). ## Acceptance criteria - [ ] no `router.navigate` inside the guard; specs cover unauthenticated, missing role, granted - [ ] no role data logged to the console Size: **S**. Returning `RedirectCommand` works today; the *throw* variant needs Angular 22.2. **Links:** Throw variant needs #1165. --- _Filed from the 2026-10-02 spikersoft-angular `pnpm outdated` changelog review._
spikerj added the enhancement label 2026-10-02 04:44:19 +00:00
Sign in to join this conversation.