Sub topic 2
Redirecting with a UrlTree
Assume basic Angular routing, TypeScript, dependency injection, and RxJS. Guards decide whether navigation may continue. Resolvers load data before the destination component activates.
Redirecting with a `UrlTree`
A guard should return true to allow navigation. To redirect, return a UrlTree, which is Angular's structured representation of a URL.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (_route, state) => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isLoggedIn()
? true
: router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url },
});
};Returning a UrlTree cancels the original navigation and starts navigation to the new URL. This is preferable to calling router.navigate() inside a guard because the router controls one navigation flow.
Other guard types
canActivateChildprotects child routes under a parent. Use it when every page in a section needs the same check.canDeactivatereceives the component being left. It can stop navigation when the component has unsaved changes.canMatchruns while Angular chooses a route. Returningfalsemakes that route unavailable for the current navigation. This is useful for role-based route selection and can prevent an unauthorized lazy route from loading.
import { CanDeactivateFn } from '@angular/router';
export interface HasUnsavedChanges {
hasUnsavedChanges(): boolean;
}
export const leaveGuard: CanDeactivateFn<HasUnsavedChanges> = component =>
component.hasUnsavedChanges()
? window.confirm('Leave without saving?')
: true;Guard and resolver order
Angular first matches route configuration, including canMatch. When leaving a route, it checks canDeactivate. For the new route, parent and child guards run before resolvers. Resolvers run only after guards allow navigation, and the router waits for their values.
Loading data with `ResolveFn`
A resolver returns the data needed by a route. The router waits for an Observable or Promise to complete.
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { Product, ProductService } from './product.service';
export const productResolver: ResolveFn<Product> = route => {
const id = route.paramMap.get('id')!;
return inject(ProductService).getById(id);
};Attach it with resolve: { product: productResolver }. The component can read product from ActivatedRoute.data. Slow guards and resolvers delay activation, so show navigation progress when requests may take noticeable time.
Exercise
Which return value should a guard use to send an anonymous user to /login?
Show answer
Return a UrlTree, such as router.createUrlTree(['/login']).