Problem Statement
How can guards or navigation handle errors and redirects cleanly?
Explanation
Guards can return a UrlTree to redirect without side effects. Subscribe to router.events and handle NavigationError for global logging. In guards/resolvers, map server errors to a safe UrlTree (e.g., /error) to avoid half-rendered screens.
Code Solution
SolutionRead Only
canActivate(): Observable<boolean|UrlTree> {
return this.api.isAllowed().pipe(
map(ok => ok || this.router.createUrlTree(['/forbidden'])),
catchError(() => of(this.router.createUrlTree(['/error'])))
);
}
this.router.events.subscribe(e => {
if(e instanceof NavigationError){ /* report */ }
});