Blog

Part 20 · RxJS in Modern Angular: Observables, toSignal and takeUntilDestroyed

Some Angular APIs, like HttpClient, still hand you RxJS Observables. This part covers Observables in brief, toSignal, toObservable, takeUntilDestroyed, and the jobs where RxJS is still the right tool, like a search box.

Signals hold a value. Some things in an app are better described as a series of values over time: key presses, ticks of a timer, answers from a server. Angular has used the RxJS library for those for years, and parts of it still do. HttpClient from Part 18 hands you its responses that way.

This part covers Observables, the RxJS type for a stream of values, in a few minutes. Then it covers the bridges between them and signals: toSignal, toObservable and takeUntilDestroyed. It ends with the jobs where RxJS is still the better tool, like a search box that waits for you to stop typing. It builds on signals from Part 3, DestroyRef from Part 10 and services from Part 13. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts. It makes an Observable that sends two numbers, and a button that listens to it.

// src/app/app.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<button (click)="listen()">Subscribe</button>`,
})
export class App {
  private readonly numbers$ = new Observable<number>((subscriber) => {
    console.log('started');
    subscriber.next(1);
    subscriber.next(2);
    subscriber.complete();
  });

  constructor() {
    console.log('page ready');
  }

  protected listen() {
    this.numbers$.subscribe((n) => console.log('got', n));
  }
}

Open the console (F12) and guess before you run it. When the page loads, does started appear? Then click Subscribe twice. How many times does started appear now?

When the page loads, the console shows only:

page ready

Click Subscribe twice, and it adds:

started
got 1
got 2
started
got 1
got 2

The function inside the Observable didn’t run when we made it. It ran once for each subscribe, from the start each time.

Observables in two minutes

An Observable is a recipe for a stream of values. It does nothing until someone subscribes. Then it can send any number of values with next, and finish in one of two ways: complete (done, no more values) or error (something failed, no more values).

That’s the difference from a Promise. A Promise gives one value, and it starts working as soon as you make it. An Observable can give many values, and starts only when you subscribe.

The $ at the end of numbers$ is a naming habit: it marks a field that holds an Observable. RxJS doesn’t need it, but you’ll see it everywhere.

You rarely write new Observable yourself. RxJS has functions that make common streams. interval(100) sends 0, 1, 2 and so on, one number every 100 milliseconds, forever. You change a stream with operators, passed to pipe. Each operator takes a stream and gives back a new one:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { interval, map, take } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<p>Last value: {{ last() }}</p>`,
})
export class App {
  protected readonly last = signal('none yet');

  constructor() {
    interval(100)
      .pipe(
        take(3),
        map((n) => `tick ${n}`),
      )
      .subscribe({
        next: (text) => {
          console.log(text);
          this.last.set(text);
        },
        complete: () => console.log('done'),
      });
  }
}
  • take(3) lets the first three values through, then completes the stream.
  • map changes each value, like an array’s map. Here it turns 0 into tick 0.
  • subscribe can take an object with a next, an error and a complete function. You give only the ones you need.

Wait a moment after the page loads. The console shows:

tick 0
tick 1
tick 2
done

and the page shows:

Last value: tick 2

We put each value into a signal, so the screen updates. A plain field wouldn’t, for the reason from Part 3: a timer doesn’t tell Angular anything.

subscribe returns a Subscription. Its unsubscribe() method stops the stream for that subscriber. This one completed on its own after three values, so there was nothing to stop. A stream that never completes, like interval(100) without take, keeps running until someone unsubscribes, even after the component is gone. We’ll deal with that below.

One more word: cold and hot. The stream in Try this first was cold: each subscriber got its own run from the start. A hot stream is shared, and a subscriber gets only the values sent after it joined. Key presses are hot. So is a Subject, which we’ll meet below.

toSignal: from an Observable to a signal

Calling subscribe and copying each value into a signal by hand is common enough that Angular does it for you. toSignal from @angular/core/rxjs-interop subscribes to an Observable and gives you a read-only signal that holds its latest value:

// src/app/app.ts
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval, map, take } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<p>Ticks: {{ ticks() }}</p>`,
})
export class App {
  protected readonly ticks = toSignal(
    interval(100).pipe(
      take(3),
      map((n) => n + 1),
    ),
    { initialValue: 0 },
  );
}

After a moment, the page shows:

Ticks: 3

A few things happen here that you’d otherwise write by hand:

  • toSignal subscribes straight away, when the field is created. It doesn’t wait for the template to read the signal.
  • It unsubscribes when the component is destroyed. To know which component it belongs to, it must be called in an injection context, like inject() and effect() (Part 13). A field initializer or the constructor is fine. A click handler isn’t.
  • The signal is read-only. Only the Observable changes it.

Before the first value: initialValue

An Observable might not have a value yet when you subscribe. The timer above sends its first number a moment later. So toSignal needs to know what the signal holds until then. That’s initialValue. Leave it out, and the signal holds undefined until the first value, and its type says so. Here’s what that does to a computed:

// src/app/app.ts
import { Component, computed } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval, map, take } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<p>Doubled: {{ doubled() }}</p>`,
})
export class App {
  protected readonly ticks = toSignal(
    interval(100).pipe(
      take(3),
      map((n) => n + 1),
    ),
  );
  protected readonly doubled = computed(() => this.ticks() * 2);
}

ng serve refuses to build it:

✘ [ERROR] TS2532: Object is possibly 'undefined'. [plugin angular-compiler]

    src/app/app.ts:17:46:
      17 │   protected readonly doubled = computed(() => this.ticks() * 2);
         ╵                                               ~~~~~~~~~~~~

TS2532 means TypeScript found a value that might be undefined, used where it can’t be. The ~~~ points at this.ticks(). (The real output starts the path with your project’s folder.) Without initialValue, ticks is a Signal<number | undefined>: before the first tick there is no number, and undefined * 2 isn’t something TypeScript lets through.

The fix is the initialValue: 0 we had before. Then the type is Signal<number>. If “nothing yet” really is a state you want to show, keep the undefined and handle it in the template with @if, or pass initialValue: null.

There’s a third option, requireSync: true. It tells toSignal that the Observable sends a value the moment you subscribe, so there’s no gap and no undefined. Some Observables do that, like the BehaviorSubject in the “In older code” section below. If the Observable doesn’t, toSignal throws error NG0601, which says that toSignal() was called with requireSync but the Observable did not emit synchronously. Use it only when you’re sure.

When the Observable fails

When the Observable sends an error, toSignal keeps the error, and reading the signal throws it. Here we load a list from /books.json with HttpClient, but the file isn’t in public/:

// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';

interface Book {
  id: number;
  title: string;
}

@Component({
  selector: 'app-root',
  template: `
    <h2>Books</h2>
    @for (book of books(); track book.id) {
      <p>{{ book.title }}</p>
    }
  `,
})
export class App {
  private readonly http = inject(HttpClient);
  protected readonly books = toSignal(this.http.get<Book[]>('/books.json'), {
    initialValue: [],
  });
}
Books

The page shows only the heading. The console has two lines. The first is the browser’s own:

Failed to load resource: the server responded with a status of 404 (Not Found)

The second starts with ERROR HttpErrorResponse. Click it open, and you’ll see the details of the failed request, with status: 404.

Here’s what happened. The server answered 404, so the Observable from HttpClient sent an error instead of a value. toSignal kept it. When the template next read books(), the read threw that error. Angular caught it and logged it as ERROR, and the list was never drawn. The signal stays that way: every later read throws the same error.

The fix is to deal with the error inside the stream, before toSignal sees it. The catchError operator replaces an error with another Observable. Here, of(null) is an Observable that sends null and completes:

// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, of } from 'rxjs';

interface Book {
  id: number;
  title: string;
}

@Component({
  selector: 'app-root',
  template: `
    <h2>Books</h2>
    @if (books(); as list) {
      @for (book of list; track book.id) {
        <p>{{ book.title }}</p>
      }
    } @else {
      <p>Could not load the books.</p>
    }
  `,
})
export class App {
  private readonly http = inject(HttpClient);
  protected readonly books = toSignal(
    this.http.get<Book[]>('/books.json').pipe(catchError(() => of(null))),
    { initialValue: [] },
  );
}

Now books is a Signal<Book[] | null>, and null means “it failed”. The browser still logs its 404 line, because the request really did fail, but Angular logs no error. The page shows:

Books
Could not load the books.

toSignal gives you a value and nothing else. If you also want “loading” and “failed” as states, resource and httpResource from Part 19 give you those without the extra code.

toObservable: from a signal to an Observable

The bridge goes the other way too. toObservable(signal) gives you an Observable that sends the signal’s value: the current one first, then the new one after each change.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';

@Component({
  selector: 'app-root',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="addThree()">Add three</button>
  `,
})
export class App {
  protected readonly count = signal(0);

  constructor() {
    toObservable(this.count).subscribe((n) => console.log('count is', n));
  }

  protected addThree() {
    this.count.update((n) => n + 1);
    this.count.update((n) => n + 1);
    this.count.update((n) => n + 1);
  }
}

When the page loads, the console shows:

count is 0

Click Add three. The count goes up three times, and the console gets one line:

count is 3

toObservable watches the signal with an effect (Part 8). Like a template, an effect runs after your code has finished, so it sees only the last value. That’s fine for state, where only the latest value matters. It’s wrong if you need every single change. Then send the values through a Subject yourself.

toObservable needs an injection context too, and its stream completes when the component is destroyed. Subscribing to it in the constructor, as here, is safe.

The bridge in one picture

Here are both bridges in the search box we’ll build below. The signal side holds state the template reads and writes. The RxJS side does the timing work.

signal world RxJS world query: 'ang' toObservable() Observable of texts an effect sends the latest value template (input) and results() query.set() reads debounceTime(300) distinctUntilChanged() switchMap(search) results(): Book[] toSignal() Observable of Book[] subscribes straight away; initialValue until the first value When the component is destroyed: toSignal unsubscribes, toObservable's stream completes. values reads a signal event sets a signal

toObservable carries a signal into RxJS; toSignal brings the result back as a signal the template reads.

takeUntilDestroyed: stopping a subscription with the component

toSignal and toObservable clean up for you. A subscribe you write yourself doesn’t. Here’s the leak that causes. A Subject is an Observable you can push values into with next. It’s hot: every subscriber gets the same values, from the moment it subscribed. A service holds one, and a child component listens to it:

// src/app/app.ts
import { Component, inject, Service, signal } from '@angular/core';
import { Subject } from 'rxjs';

@Service()
export class Messages {
  readonly sent = new Subject<string>();
}

@Component({
  selector: 'app-listener',
  template: `<p>Listening</p>`,
})
export class Listener {
  constructor() {
    inject(Messages).sent.subscribe((text) => console.log('listener got', text));
  }
}

@Component({
  selector: 'app-root',
  imports: [Listener],
  template: `
    @if (showListener()) {
      <app-listener />
    }
    <button (click)="send()">Send</button>
    <button (click)="showListener.set(false)">Remove listener</button>
  `,
})
export class App {
  private readonly messages = inject(Messages);
  protected readonly showListener = signal(true);
  private sentCount = 0;

  protected send() {
    this.sentCount++;
    this.messages.sent.next(`message ${this.sentCount}`);
  }
}

Click Send, then Remove listener, then Send again. The page shows:

SendRemove listener

The listener is gone from the page. But the console shows:

listener got message 1
listener got message 2

The second line came from a component that no longer exists. The Subject lives in a root service, so it outlives the component, and it still holds the subscription. Every time the listener is shown again, one more subscription piles up.

The fix is to unsubscribe when the component is destroyed. With DestroyRef from Part 10, that’s:

// src/app/app.ts
import { Component, DestroyRef, inject, Service, signal } from '@angular/core';
import { Subject } from 'rxjs';

@Service()
export class Messages {
  readonly sent = new Subject<string>();
}

@Component({
  selector: 'app-listener',
  template: `<p>Listening</p>`,
})
export class Listener {
  constructor() {
    const subscription = inject(Messages).sent.subscribe((text) =>
      console.log('listener got', text),
    );
    inject(DestroyRef).onDestroy(() => subscription.unsubscribe());
  }
}

@Component({
  selector: 'app-root',
  imports: [Listener],
  template: `
    @if (showListener()) {
      <app-listener />
    }
    <button (click)="send()">Send</button>
    <button (click)="showListener.set(false)">Remove listener</button>
  `,
})
export class App {
  private readonly messages = inject(Messages);
  protected readonly showListener = signal(true);
  private sentCount = 0;

  protected send() {
    this.sentCount++;
    this.messages.sent.next(`message ${this.sentCount}`);
  }
}

Do the same three clicks. The console shows one line:

listener got message 1

takeUntilDestroyed() is the same thing as an operator. Put it last in the pipe, and the stream completes when the component is destroyed, which ends the subscription:

// src/app/app.ts
import { Component, inject, Service, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject } from 'rxjs';

@Service()
export class Messages {
  readonly sent = new Subject<string>();
}

@Component({
  selector: 'app-listener',
  template: `<p>Listening</p>`,
})
export class Listener {
  constructor() {
    inject(Messages)
      .sent.pipe(takeUntilDestroyed())
      .subscribe((text) => console.log('listener got', text));
  }
}

@Component({
  selector: 'app-root',
  imports: [Listener],
  template: `
    @if (showListener()) {
      <app-listener />
    }
    <button (click)="send()">Send</button>
    <button (click)="showListener.set(false)">Remove listener</button>
  `,
})
export class App {
  private readonly messages = inject(Messages);
  protected readonly showListener = signal(true);
  private sentCount = 0;

  protected send() {
    this.sentCount++;
    this.messages.sent.next(`message ${this.sentCount}`);
  }
}
listener got message 1

With no argument, takeUntilDestroyed() finds the component’s DestroyRef itself. So, like inject(), it only works in an injection context.

Worked example: subscribing from a click handler

Sometimes you only start listening when the user asks. Let’s give the listener a Listen button and move the subscription into its handler:

// src/app/app.ts
import { Component, inject, Service, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject } from 'rxjs';

@Service()
export class Messages {
  readonly sent = new Subject<string>();
}

@Component({
  selector: 'app-listener',
  template: `<button (click)="listen()">Listen</button>`,
})
export class Listener {
  private readonly messages = inject(Messages);

  protected listen() {
    this.messages.sent
      .pipe(takeUntilDestroyed())
      .subscribe((text) => console.log('listener got', text));
  }
}

@Component({
  selector: 'app-root',
  imports: [Listener],
  template: `
    @if (showListener()) {
      <app-listener />
    }
    <button (click)="send()">Send</button>
    <button (click)="showListener.set(false)">Remove listener</button>
  `,
})
export class App {
  private readonly messages = inject(Messages);
  protected readonly showListener = signal(true);
  private sentCount = 0;

  protected send() {
    this.sentCount++;
    this.messages.sent.next(`message ${this.sentCount}`);
  }
}

It builds. Click Listen, and the console shows an error:

ERROR RuntimeError: NG0203: takeUntilDestroyed() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://v22.angular.dev/errors/NG0203

This is NG0203 again, the error we met with effect() in Part 8 and inject() in Part 13. With no argument, takeUntilDestroyed() has to find the component’s DestroyRef itself, by injecting it. A click handler runs long after the component was created, so there’s nothing to inject from. The error is thrown before subscribe is called, so the listener never subscribes: click Send now, and nothing is logged.

The fix is to get the DestroyRef while the component is being created, in a field, and pass it to takeUntilDestroyed later:

// src/app/app.ts
import { Component, DestroyRef, inject, Service, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject } from 'rxjs';

@Service()
export class Messages {
  readonly sent = new Subject<string>();
}

@Component({
  selector: 'app-listener',
  template: `<button (click)="listen()">Listen</button>`,
})
export class Listener {
  private readonly messages = inject(Messages);
  private readonly destroyRef = inject(DestroyRef);

  protected listen() {
    this.messages.sent
      .pipe(takeUntilDestroyed(this.destroyRef))
      .subscribe((text) => console.log('listener got', text));
  }
}

@Component({
  selector: 'app-root',
  imports: [Listener],
  template: `
    @if (showListener()) {
      <app-listener />
    }
    <button (click)="send()">Send</button>
    <button (click)="showListener.set(false)">Remove listener</button>
  `,
})
export class App {
  private readonly messages = inject(Messages);
  protected readonly showListener = signal(true);
  private sentCount = 0;

  protected send() {
    this.sentCount++;
    this.messages.sent.next(`message ${this.sentCount}`);
  }
}

Click Listen, Send, Remove listener and Send. The console shows:

listener got message 1

One rule, two ways to follow it: in the constructor or a field, takeUntilDestroyed() with no argument. Anywhere else, pass a DestroyRef you injected earlier.

When RxJS is still the right tool

Signals are good at holding the current value. They have no idea of time. They can’t say “wait until the user stops typing”, or “drop the answer to an old question”. RxJS operators can. That’s where RxJS still earns its place in a new app: input that arrives over time and has to be timed, combined or cancelled.

We want a box that filters a list of books as you type. We don’t want a request for every key press, and we never want an old, slow answer to overwrite a newer one. The books come from a file in public/. Save this as public/books.json in your project:

[
  { "id": 1, "title": "Angular Basics" },
  { "id": 2, "title": "Angular Signals Step by Step" },
  { "id": 3, "title": "RxJS for Everyone" },
  { "id": 4, "title": "React Hooks Explained" },
  { "id": 5, "title": "Rust Without Fear" }
]

Then the component:

// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, map, switchMap, tap } from 'rxjs';

interface Book {
  id: number;
  title: string;
}

@Component({
  selector: 'app-root',
  template: `
    <input #box placeholder="Search" (input)="query.set(box.value)" />
    <ul>
      @for (book of results(); track book.id) {
        <li>{{ book.title }}</li>
      } @empty {
        <li>No books</li>
      }
    </ul>
  `,
})
export class App {
  private readonly http = inject(HttpClient);
  protected readonly query = signal('');

  protected readonly results = toSignal(
    toObservable(this.query).pipe(
      debounceTime(300),
      distinctUntilChanged(),
      tap((query) => console.log(`searching for "${query}"`)),
      switchMap((query) => this.search(query)),
    ),
    { initialValue: [] },
  );

  private search(query: string) {
    const text = query.toLowerCase();
    return this.http
      .get<Book[]>('/books.json')
      .pipe(map((books) => books.filter((book) => book.title.toLowerCase().includes(text))));
  }
}

Read the pipe from the top:

  • toObservable(this.query) turns the signal the input writes into a stream of search texts.
  • debounceTime(300) holds each value back until 300 milliseconds pass with no newer one. While you’re typing, nothing goes through. When you stop, only the last text does.
  • distinctUntilChanged() drops a value that’s the same as the one before it. If you quickly type a letter and delete it again, the debounce lets the old text through, and distinctUntilChanged drops it, so there’s no second search for the same text.
  • tap runs a function for each value and passes the value on unchanged. It’s for side effects like logging. We use it to see which searches really happen.
  • switchMap turns each search text into a new Observable, the HTTP request, and sends on that request’s answer. When a newer text arrives, it unsubscribes from the old request, which cancels it. An old answer can never land after a new one.
  • toSignal brings the result back as a signal for the template, with [] until the first answer.

search builds the request: HttpClient.get returns an Observable of the file’s contents (Part 18), and map keeps the books whose title contains the text. (The real filter would be on a server; here the file stands in for it.) #box is a template reference variable from Part 2: it names the input, so (input) can pass its value to query.set.

After the page loads and the debounce passes, the console shows one search for the empty text:

searching for ""

and the page shows every book:

Angular Basics
Angular Signals Step by Step
RxJS for Everyone
React Hooks Explained
Rust Without Fear

Now type a, then an, then ang quickly, and stop. The console gets one line, not three:

searching for "ang"
Angular Basics
Angular Signals Step by Step

Type angu, quickly go back to ang, and stop. The debounce lets ang through, and distinctUntilChanged drops it, because the last search was ang too. Then type vue and stop. The console gets one more line, for vue only:

searching for "vue"

No title matches, so @empty from Part 4 shows:

No books

Try writing this with signals alone. You’d need a setTimeout to wait, a field to remember the last text, and a counter to ignore answers that come back out of order. That’s what the three operators do for you.

Streams of events: fromEvent

fromEvent(target, 'eventName') turns DOM events into an Observable. It adds the listener when you subscribe and removes it when you unsubscribe. With toSignal, that’s the component’s lifetime. Here’s a page that shows the last key you pressed anywhere on it:

// src/app/app.ts
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { filter, fromEvent, map } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<p>Last key: {{ lastKey() }}</p>`,
})
export class App {
  protected readonly lastKey = toSignal(
    fromEvent<KeyboardEvent>(document, 'keydown').pipe(
      filter((event) => event.key !== 'Shift'),
      map((event) => event.key),
    ),
    { initialValue: 'none' },
  );
}

fromEvent<KeyboardEvent> is a generic, as in Part 3: it tells TypeScript what kind of event comes out, so event.key type-checks. filter lets through only the values its function returns true for, here every key except Shift on its own. Press a, then Enter. The page shows:

Last key: Enter

For an event on an element in your own template, keep using (keydown) from Part 2, or a host listener from Part 11. fromEvent is for things outside your template, like document or window, and for when you want operators on the events. interval is the same kind of source for time, as we saw above. Always end it with take, takeUntilDestroyed or toSignal, so it stops.

Outputs from Observables

Two more bridges, for outputs (Part 6). outputFromObservable(stream$) declares an output that emits each value the Observable sends, for a component that already has its events as a stream. outputToObservable(child.someOutput) goes the other way and gives you an Observable of an output’s events. Both live in @angular/core/rxjs-interop. In new code, a plain output() is usually all you need.

Signals or Observables?

They’re good at different jobs.

Signal Observable
Holds one current value, always readable usually nothing; values pass through (a BehaviorSubject is the exception)
Good for state: what the screen shows now events and timing: what happened, when
Has a value always, from the start only after it sends one, to a subscriber
Reading call it, count() subscribe, then clean up
Time operators none debounceTime, switchMap, take…

So: keep state in signals. Reach for RxJS when the problem is about time or a series of events. Cross the bridge with toSignal as soon as you can, and let the template read signals.

For a single request driven by a signal, Part 19 shows a third choice: resource and httpResource load data when a signal changes and give you loading and error states. A search box that needs debouncing is where RxJS still wins.

In older code

Before signals, Angular code used RxJS for state as well. You’ll meet three things.

The async pipe from Part 12 subscribes in the template and unsubscribes when the component goes: {{ count$ | async }}. Before the first value, it gives null. In new code, toSignal does the same job in the class.

A BehaviorSubject, as in the store from Part 15, is a Subject that holds a current value and sends it to each new subscriber straight away. Because it sends a value the moment you subscribe, it’s the case requireSync was made for:

// src/app/app.ts
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
    <p>Theme: {{ theme() }}</p>
    <button (click)="dark()">Dark</button>
  `,
})
export class App {
  private readonly theme$ = new BehaviorSubject('light');
  protected readonly theme = toSignal(this.theme$, { requireSync: true });

  protected dark() {
    this.theme$.next('dark');
  }
}

theme is a Signal<string>, with no undefined. Click Dark, and the page shows:

Theme: dark
Dark

That’s a good first step when you move an old store to signals: keep the store as it is, and wrap its streams with toSignal in the components.

The third is the destroy Subject: a private destroy$ = new Subject<void>(), takeUntil(this.destroy$) on each stream, and this.destroy$.next() in ngOnDestroy(). It’s the long form of takeUntilDestroyed().

Best practices

  • Turn Observables into signals with toSignal, close to where they come from. The template then reads signals like everywhere else. It replaces the async pipe and a subscribe that copies values into a field.
  • Give toSignal an initialValue unless “no value yet” is a state you want to show. It keeps undefined out of the type and out of every computed that reads it.
  • End every subscribe to a long-lived stream with takeUntilDestroyed(). That means a Subject in a service, interval or fromEvent. Call it in the constructor or a field, or pass a DestroyRef you injected there. It replaces ngOnDestroy with a destroy Subject. (A single HTTP request finishes by itself, but takeUntilDestroyed also stops its callback running after the component is gone.)
  • Keep state in signals, and use RxJS for time and events. Debouncing, cancelling old requests and combining streams are what operators are for. A value the screen shows is what a signal is for.
  • Handle errors inside the stream, with catchError, before toSignal. Otherwise reading the signal throws.

Tips and traps

  • A stream that does nothing. You built it with pipe, but nothing subscribes to it, so no tap logs and no request goes out. Call subscribe, or hand it to toSignal, which subscribes straight away.
  • A listener that keeps logging after its component is gone. A subscribe to a long-lived stream in a service, with no cleanup. Add takeUntilDestroyed().
  • takeUntilDestroyed() or toSignal in a click handler. The console shows NG0203. Inject DestroyRef in a field and pass it, or create the toSignal in a field.
  • TS2532: Object is possibly 'undefined' on a toSignal signal. You left out initialValue. Add one, or handle the undefined in the template.
  • The whole page fails because one request failed. An error in the Observable makes the signal throw when read. Catch it in the pipe and turn it into a value the template can show.
  • Expecting toObservable to send every change. Several changes in one handler arrive as one value, the last. Use a Subject if every value matters.
  • mergeMap or concatMap where you meant switchMap. Neither cancels an old request. With mergeMap, an old answer can arrive after a new one and overwrite it. With concatMap, each search waits for every older one. For a search, use switchMap.

Keep state in signals, use RxJS for things that happen over time, and cross between them with toSignal and toObservable.

Exercises

Exercise 1. Rewrite this component without the constructor and without set, using toSignal. The page should end up showing Countdown: 1.

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { interval, map, take } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<p>Countdown: {{ left() }}</p>`,
})
export class App {
  protected readonly left = signal(3);

  constructor() {
    interval(100)
      .pipe(
        take(3),
        map((n) => 3 - n),
      )
      .subscribe((n) => this.left.set(n));
  }
}
Countdown: 1

Exercise 2. Change the search box so it doesn’t search for a single letter. An empty box should still show every book. Typing a and stopping should log nothing. Hint: the filter operator from the fromEvent example.

Exercise 3. Show how many times the page has been clicked, anywhere, using fromEvent(document, 'click') and toSignal. Add a button labelled Click me so there’s something to click. After two clicks, the page should show Clicks: 2 above the button. Hint: map‘s function gets a second argument, the index of the value: 0, 1, 2…

Answers

1. The subscribe and the set become one toSignal. The starting 3 becomes the initialValue:

// src/app/app.ts
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { interval, map, take } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `<p>Countdown: {{ left() }}</p>`,
})
export class App {
  protected readonly left = toSignal(
    interval(100).pipe(
      take(3),
      map((n) => 3 - n),
    ),
    { initialValue: 3 },
  );
}

After a moment, the page shows:

Countdown: 1

2. Add a filter after distinctUntilChanged that lets through an empty text or one of two letters or more:

[
  { "id": 1, "title": "Angular Basics" },
  { "id": 2, "title": "Angular Signals Step by Step" },
  { "id": 3, "title": "RxJS for Everyone" },
  { "id": 4, "title": "React Hooks Explained" },
  { "id": 5, "title": "Rust Without Fear" }
]
// src/app/app.ts
import { HttpClient } from '@angular/common/http';
import { Component, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, filter, map, switchMap, tap } from 'rxjs';

interface Book {
  id: number;
  title: string;
}

@Component({
  selector: 'app-root',
  template: `
    <input #box placeholder="Search" (input)="query.set(box.value)" />
    <ul>
      @for (book of results(); track book.id) {
        <li>{{ book.title }}</li>
      } @empty {
        <li>No books</li>
      }
    </ul>
  `,
})
export class App {
  private readonly http = inject(HttpClient);
  protected readonly query = signal('');

  protected readonly results = toSignal(
    toObservable(this.query).pipe(
      debounceTime(300),
      distinctUntilChanged(),
      filter((query) => query.length !== 1),
      tap((query) => console.log(`searching for "${query}"`)),
      switchMap((query) => this.search(query)),
    ),
    { initialValue: [] },
  );

  private search(query: string) {
    const text = query.toLowerCase();
    return this.http
      .get<Book[]>('/books.json')
      .pipe(map((books) => books.filter((book) => book.title.toLowerCase().includes(text))));
  }
}

query.length !== 1 is true for an empty text and for two letters or more. Wait for the first search, then type a and stop. The console shows only the first search:

searching for ""

Type ru, and it searches:

searching for "ru"
Rust Without Fear

3. map((event, index) => index + 1) turns the first click into 1, the second into 2:

// src/app/app.ts
import { Component } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { fromEvent, map } from 'rxjs';

@Component({
  selector: 'app-root',
  template: `
    <p>Clicks: {{ clicks() }}</p>
    <button>Click me</button>
  `,
})
export class App {
  protected readonly clicks = toSignal(
    fromEvent(document, 'click').pipe(map((event, index) => index + 1)),
    { initialValue: 0 },
  );
}

Click Click me twice. The page shows:

Clicks: 2
Click me

What’s next

So far, our forms have been a single input wired up by hand. In Part 21, we’ll build real forms with Signal Forms: a model signal, fields bound with [formField], and validation.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.