Sub topic 3
Reading Resolved Data in an Angular Component
This chapter assumes basic TypeScript, Angular components and services, routing, RxJS, and dependency injection.
Reading resolved data
A resolver loads data before the router activates a component. The key in the route’s resolve map becomes the data name. With withComponentInputBinding(), Angular binds that data directly to a component input:
import { Component, input } from '@angular/core';
import { Product } from './product.service';
@Component({
selector: 'app-product-detail',
standalone: true,
template: `<h1>{{ product().name }}</h1>`,
})
export class ProductDetailComponent {
product = input.required<Product>();
}Configure the router with provideRouter(routes, withComponentInputBinding()). Without input binding, inject ActivatedRoute and read route.snapshot.data['product'].
Handling resolver failures
A failed resolver can cancel navigation. For a user-friendly result, catch the error and return a redirect:
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, of } from 'rxjs';
import { Product, ProductService } from './product.service';
export const productResolver: ResolveFn<Product | RedirectCommand> = route => {
const router = inject(Router);
return inject(ProductService).getById(route.paramMap.get('id')!).pipe(
catchError(() => of(new RedirectCommand(router.parseUrl('/not-found')))),
);
};Slow navigation and testing
The router waits for asynchronous guards and resolvers. Show progress from navigation events, such as NavigationStart and NavigationEnd, in a shared loading service. Always complete or limit resolver streams. An Observable that never completes can leave navigation waiting forever.
| Task | Useful test focus |
|---|---|
| Guard | Allowed result or redirect URL |
| Resolver | Returned data or error redirect |
Run functional guards inside an injection context:
const result = TestBed.runInInjectionContext(() =>
authGuard({} as ActivatedRouteSnapshot, { url: '/admin' } as RouterStateSnapshot),
);
expect(router.serializeUrl(result as UrlTree))
.toBe('/login?returnUrl=%2Fadmin');Security and legacy guards
A guard improves navigation behavior and user experience. It is not a security boundary because users can modify client-side JavaScript or send requests without using the application. Enforce authorization on the server for every protected operation.
Modern Angular favors functional guards and resolvers with inject(). Older applications may use class-based guards such as implements CanActivate. They still work, but new code should generally use CanActivateFn, ResolveFn, and related function types.
Exercise
What happens if a resolver returns an Observable that never completes?
Show answer
Navigation remains pending because the router waits for the resolver to finish.