Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 74 ยท Projects

Project: Movie Search App

Build a movie search app in Angular with HttpClient, a debounced search box using RxJS, a detail route and honest loading and error states, with a fake API and runnable stand-ins.

Search-as-you-type is one of the most common features on the web, and one of the easiest to get subtly wrong. If every key press sends a request, you waste the server's time. If responses arrive out of order, an old answer overwrites a new one. If the request fails, the screen silently stays empty. A good Angular solution fixes all three with a handful of RxJS operators.

This project combines HttpClient: Requests and Responses, RxJS Operators, Signals and RxJS Interop and Route Parameters and Navigation. Our earlier Weather Dashboard used resource(); here we use the classic operator pipeline, which you will meet in many existing codebases.

Real versus stand-in. The typescript and html blocks are the real Angular app, to read and copy into a project made with ng new. The endpoint https://api.example.com/movies is an invented example: point it at any movie API you use, and keep keys on a server you control, never in the browser bundle. The site cannot compile Angular or call a real API, so the runnable examples re-implement the logic (debounce, cancel the older request, three states) with a fake API made of timers.

Step 1: the plan

flowchart LR
  I["Search box<br/>(query signal)"] --> D["debounceTime(300)<br/>distinctUntilChanged()"]
  D --> F["filter: 2+ characters"]
  F --> S["switchMap<br/>cancel the previous request"]
  S --> H["HttpClient<br/>GET /movies?search=..."]
  H --> V["Template:<br/>idle / loading / error / results"]
  V --> R["Click a result<br/>route /movie/:id"]

Each operator solves one problem: too many requests, repeated values, tiny queries, stale responses.

The files:

TEXT
src/app/movies/
  movie.ts              (types)
  movie.service.ts      (HTTP only)
  movie-search.ts       (search page)
  movie-detail.ts       (detail page, route /movie/:id)

Step 2: types and the service

TypeScript
// movie.ts
export interface MovieSummary {
  id: string;
  title: string;
  year: number;
}

export interface MovieDetail extends MovieSummary {
  overview: string;
  rating: number;
}
TypeScript
// movie.service.ts
import { HttpClient, HttpParams } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { MovieDetail, MovieSummary } from './movie';

@Injectable({ providedIn: 'root' })
export class MovieService {
  private readonly http = inject(HttpClient);
  private readonly base = 'https://api.example.com/movies'; // invented endpoint

  search(query: string): Observable<MovieSummary[]> {
    const params = new HttpParams().set('search', query);
    return this.http.get<MovieSummary[]>(this.base, { params });
  }

  get(id: string): Observable<MovieDetail> {
    return this.http.get<MovieDetail>(`${this.base}/${encodeURIComponent(id)}`);
  }
}

HttpParams encodes the query for you, so a search for Tom & Jerry cannot break the URL. The service knows the URL; components do not.

Step 3: the search page

The component keeps the text in a signal, converts it to an observable with toObservable, pipes it through the operators, and converts the final stream back to a signal with toSignal. The template then only reads signals.

TypeScript
// movie-search.ts
import { Component, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { RouterLink } from '@angular/router';
import { catchError, debounceTime, distinctUntilChanged, map, Observable, of, startWith, switchMap } from 'rxjs';
import { MovieSummary } from './movie';
import { MovieService } from './movie.service';

type SearchState =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'error' }
  | { status: 'done'; results: MovieSummary[] };

@Component({
  selector: 'app-movie-search',
  imports: [RouterLink],
  template: `
    <label>Search movies
      <input [value]="query()" (input)="query.set($any($event.target).value)" />
    </label>

    @switch (state().status) {
      @case ('idle') { <p>Type at least two characters.</p> }
      @case ('loading') { <p role="status">Searching...</p> }
      @case ('error') { <p role="alert">Could not load movies. Try again.</p> }
      @case ('done') {
        <ul>
          @for (m of results(); track m.id) {
            <li><a [routerLink]="['/movie', m.id]">{{ m.title }} ({{ m.year }})</a></li>
          } @empty { <li>No movies found.</li> }
        </ul>
      }
    }
  `,
})
export class MovieSearch {
  private readonly movies = inject(MovieService);
  protected readonly query = signal('');

  protected readonly state = toSignal(
    toObservable(this.query).pipe(
      debounceTime(300),
      map(q => q.trim()),
      distinctUntilChanged(),
      switchMap((q): Observable<SearchState> =>
        q.length < 2
          ? of({ status: 'idle' })
          : this.movies.search(q).pipe(
              map(results => ({ status: 'done', results }) as SearchState),
              catchError(() => of({ status: 'error' } as SearchState)),
              startWith({ status: 'loading' } as SearchState),
            ),
      ),
    ),
    { initialValue: { status: 'idle' } as SearchState },
  );

  protected results(): MovieSummary[] {
    const s = this.state();
    return s.status === 'done' ? s.results : [];
  }
}

Read the pipeline slowly:

  • debounceTime(300) waits until typing pauses for 300 ms.
  • map(q => q.trim()) and distinctUntilChanged() mean typing a space does not repeat the same search.
  • switchMap starts the new request and cancels the previous one. Angular's HttpClient aborts the underlying request when it is unsubscribed, so an old answer can never replace a new one.
  • catchError sits inside the switchMap. If it were outside, one failed request would complete the whole pipeline and the search box would stop working.
  • startWith(loading) emits the loading state immediately for each new search.

The union type SearchState makes impossible states impossible: you cannot have results while loading. The @switch on state().status is the template counterpart.

Step 4: the detail route

TypeScript
// app.routes.ts (excerpt)
export const routes: Routes = [
  { path: '', component: MovieSearch },
  { path: 'movie/:id', component: MovieDetailPage },
];

With withComponentInputBinding() in provideRouter, the :id segment arrives as an input, and an httpResource loads the movie (Route Parameters and Navigation, linkedSignal, resource and httpResource):

TypeScript
// movie-detail.ts
import { Component, input } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { RouterLink } from '@angular/router';
import { MovieDetail } from './movie';

@Component({
  selector: 'app-movie-detail',
  imports: [RouterLink],
  template: `
    <a routerLink="/">Back to search</a>
    @if (movie.isLoading()) { <p role="status">Loading...</p> }
    @else if (movie.error()) { <p role="alert">Movie not found.</p> }
    @else if (movie.value(); as m) {
      <h1>{{ m.title }} ({{ m.year }})</h1>
      <p>Rating: {{ m.rating }} / 10</p>
      <p>{{ m.overview }}</p>
    }
  `,
})
export class MovieDetailPage {
  id = input.required<string>();
  protected readonly movie = httpResource<MovieDetail>(
    () => `https://api.example.com/movies/${encodeURIComponent(this.id())}`,
  );
}

Using both styles on purpose shows the trade-off. The operator pipeline is the right tool for streams of user input; httpResource is the shorter tool for "load this thing for this parameter".

Step 5: run the logic

RxJS is not available in the runner, so this stand-in implements the same ideas with timers and a cancel flag: a debounce, a skip for short queries, cancellation of stale requests, and one failing query. The fake API takes a different time per query, so an old answer would arrive late if it were not cancelled.

TypeScript Debounce, cancel the old request, three states

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Four quick key presses sent one request, not four. A trailing space did not repeat the search. When a slow older request would have finished after a newer one, it was thrown away. And after an error the next search worked, which is what catchError inside switchMap buys you.

Step 6: see it as a UI

The second stand-in is a complete search page on the same fake API. There is a tiny hash route for the detail view, because the sandbox has no history API.

A working movie search UI

Ideas to extend it

  • Add paging with a page signal included in the request.
  • Cache results by query in a Map inside the service.
  • Add a "recent searches" list in a signal.
  • Test the pipeline with HttpTestingController and fake timers (Testing Angular Applications).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does switchMap add to a search pipeline?

    switchMap unsubscribes from the older inner observable, which makes HttpClient abort that request, so stale answers cannot overwrite fresh ones.
  2. 2. Why is catchError placed inside the switchMap callback?

    An error that reaches the outer stream ends it. Handling it inside the inner observable lets the next search start normally.
  3. 3. What is the job of debounceTime(300)?

    Only the last value of a burst of key presses is passed on, which avoids a request per keystroke.
  4. 4. Why model the state as a union type with a status field?

    Each status carries only the data it needs, and the template can switch on the status safely.

Summary

  • Keep HTTP in a service, use HttpParams for query strings, and keep real API keys on a server.
  • Turn the query signal into a stream with toObservable, then use debounceTime, distinctUntilChanged and switchMap to avoid wasted and stale requests.
  • Put catchError and startWith inside switchMap so each search has its own loading and error state.
  • Model idle, loading, error and done as one union and render it with @switch.
  • Use a route parameter plus httpResource for the detail page.

Next: Project: Realtime Chat with WebSockets.