Angular Guard Redirect Error Fix
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.
Right
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
canActivatearray - Use
UrlTreefor redirects instead of callingrouter.navigate() - Test guards with
RouterTestingModulein unit tests
Common Mistakes with guard redirect
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro