Skip to content

Angular Guard Redirect Error Fix

DodaTech Updated 2026-06-24 2 min read

In this tutorial, you'll learn about Angular Guard Redirect Error Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

The Problem

Angular route guard returns UrlTree but the navigation does not redirect.

Wrong

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(): boolean | UrlTree {
    const loggedIn = !!localStorage.getItem('token')
    if (!loggedIn) {
      return this.router.parseUrl('/login')
    }
    return true
  }
}

The guard looks correct, but if it is not applied to the route, it never runs.

Apply the guard to the route configuration:

const routes: Routes = [
  {
    path: 'dashboard',
    component: DashboardComponent,
    canActivate: [AuthGuard],
  },
  {
    path: 'login',
    component: LoginComponent,
  },
]

For redirect with query params:

canActivate(): boolean | UrlTree {
  const loggedIn = !!localStorage.getItem('token')
  if (!loggedIn) {
    return this.router.createUrlTree(['/login'], {
      queryParams: { returnUrl: this.router.url },
    })
  }
  return true
}

Expected output: unauthenticated users are redirected to /login?returnUrl=/dashboard.

Prevention

  • Add the guard to the route's canActivate array
  • Use UrlTree for redirects instead of calling router.navigate()
  • Test guards with RouterTestingModule in unit tests

Common Mistakes with guard redirect

  1. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  2. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  3. Using head and tail instead of pattern matching, causing runtime errors on empty lists

These mistakes appear frequently in real-world Angular code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between CanActivate and CanActivateChild?

CanActivate guards a route and its children. CanActivateChild only guards child routes, running when navigating to a child even if the parent is already activated.

Can I redirect with query parameters in a guard?

Yes. Use this.router.createUrlTree(['/login'], { queryParams: { returnUrl: url } }) to preserve the intended destination for post-login redirect.

How do I pass data to a guard?

Use route data or inject a service. Guards are injectable services that can access any Angular service through Dependency Injection.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro