← Back to Angular, page 2

angular-0033 · Medium mid

What is a route resolver, how does a functional ResolveFn deliver data to a component, and what are the trade-offs?

A resolver is a function that loads data before the router activates a route. The result is stored under a key in the route's resolve map and, with withComponentInputBinding, arrives as a component input of the same name. The trade-off is that navigation waits for the data, so slow resolvers make the app feel stuck.

Full answer

A resolver runs during navigation, after guards and before the component is created. The router waits until it finishes. The component then starts with its data ready, so you avoid a half-empty screen and do not need loading flags inside the component.

A functional resolver is typed as ResolveFn<T> and can use inject():

ts
export const courseResolver: ResolveFn<Course> = (route) =>
  inject(CourseService).get(route.paramMap.get('id') ?? '');

It is attached in the route: resolve: { course: courseResolver }. With provideRouter(routes, withComponentInputBinding()) the component simply declares course = input.required<Course>(). The older way reads ActivatedRoute.data. The same mechanism can compute a page title: title: courseTitleResolver.

Handling failure. If the resolver's Observable errors, the navigation is cancelled and the user stays where they were, which looks like a dead link. Catch the error and return a fallback value, or return a RedirectCommand (available from Angular 18.2), which tells the router to go to another URL instead: new RedirectCommand(router.parseUrl('/not-found')).

Trade-offs:

  • Pro: the page renders in one piece, and the data is guaranteed in the component.
  • Con: there is no visible feedback during the wait unless you show a global loading bar using router events.
  • Con: data loading blocks the whole navigation, even if the page could show its header immediately.

Many teams load the critical data in a resolver and load secondary data inside the component with a loading state. If you want instant navigation with skeleton placeholders, skip resolvers and load in the component.

Class-based resolvers (implements Resolve<T>) are legacy.

typescript
// file: course.service.ts
import { Injectable } from '@angular/core';
import { Observable, of, throwError } from 'rxjs';

export interface Course {
  id: string;
  title: string;
}

@Injectable({ providedIn: 'root' })
export class CourseService {
  private readonly all: Course[] = [
    { id: '1', title: 'Angular basics' },
    { id: '2', title: 'RxJS in practice' },
  ];

  get(id: string): Observable<Course> {
    const found = this.all.find((c) => c.id === id);
    return found ? of(found) : throwError(() => new Error('Course not found'));
  }
}

// file: resolvers.ts
import { inject } from '@angular/core';
import { RedirectCommand, ResolveFn, Router } from '@angular/router';
import { catchError, map, of } from 'rxjs';
import { Course, CourseService } from './course.service';

export const courseResolver: ResolveFn<Course> = (route) => {
  const router = inject(Router);
  return inject(CourseService)
    .get(route.paramMap.get('id') ?? '')
    .pipe(catchError(() => of(new RedirectCommand(router.parseUrl('/not-found')))));
};

export const courseTitleResolver: ResolveFn<string> = (route) =>
  inject(CourseService)
    .get(route.paramMap.get('id') ?? '')
    .pipe(
      map((course) => course.title),
      catchError(() => of('Course')),
    );

// file: course-detail.component.ts
import { Component, input } from '@angular/core';
import { Course } from './course.service';

@Component({
  selector: 'app-course-detail',
  template: `<h1>{{ course().title }}</h1>`,
})
export class CourseDetailComponent {
  // Filled from resolve: { course: courseResolver }
  course = input.required<Course>();
}

// file: app.config.ts
import { ApplicationConfig } from '@angular/core';
import { Routes, provideRouter, withComponentInputBinding } from '@angular/router';
import { CourseDetailComponent } from './course-detail.component';
import { courseResolver, courseTitleResolver } from './resolvers';

export const routes: Routes = [
  {
    path: 'courses/:id',
    component: CourseDetailComponent,
    resolve: { course: courseResolver },
    title: courseTitleResolver,
  },
];

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes, withComponentInputBinding())],
};

Angular 20.3. The service returns fixed data with `of()` so the code is self-contained. A real one would call `HttpClient`.

Key points

  • Resolvers run after guards and before the component, and block navigation until done.
  • `resolve: { key: fn }` plus `withComponentInputBinding()` gives an input named `key`.
  • A failed resolver cancels the navigation. Catch errors and return a fallback or a `RedirectCommand`.
  • Choose resolvers for critical data and component-level loading for the rest.

Common mistakes

  • Not catching errors, so a failed request silently leaves the user on the previous page.
  • Resolving many slow calls and blocking the whole navigation.
  • Reading `route.snapshot` data inside a component that is reused for different ids, and missing updates.

Follow-ups

  • When would you choose a resolver instead of loading in the component?
  • How would you show a loading bar while a resolver runs?
  • How does resolver data refresh when only the route parameter changes?

Tips

  • Give your decision rule: critical, small data in a resolver; large or optional data in the component.
  • Mention the failure case. It is where most candidates stop.
  • Say that class-based resolvers are legacy.

Evaluation rubric

  • Writes a ResolveFn and attaches it to a route.
  • Knows how data reaches the component.
  • Explains trade-offs and failures.