Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 74 ยท HTTP and RxJS

Signals and RxJS Interop

Bridge signals and RxJS in Angular with toSignal, toObservable, takeUntilDestroyed and outputFromObservable, and learn when to use which.

Modern Angular has two reactive tools, and a real app uses both. Signals hold a current value, are read synchronously and drive the template. RxJS observables describe values arriving over time: clicks, WebSocket messages, HTTP responses, debounced typing. They are not rivals. Signals are the best way to hold state a component shows, and observables are the best way to describe events and asynchronous flows. The @angular/core/rxjs-interop package provides the bridges between them.

This lesson assumes you know signals, observables and the operators. It also finishes the HTTP section: the observable that HttpClient returns, from HttpClient and interceptors, is exactly what you will bridge into a signal.

The real Angular code is read-only, because the site cannot run the Angular compiler. The runnable examples are stand-ins: a tiny Subject, a tiny signal and simplified versions of toSignal and toObservable. They show the behavior that matters (initial values, cleanup, batching), not Angular's implementation.

Two models of reactivity

The difference is easiest to see side by side.

Signal Observable
Has a current value Always Not necessarily
Read count(), synchronous, anywhere subscribe(...), a callback later
Updates reach consumers Lazily, only the latest value is seen Every emission is delivered
Cleanup Automatic, tied to the component You unsubscribe (or the operator does)
Time-based operations Not built in debounceTime, switchMap, retry...
Best at State, derived values, templates Events, streams, requests, cancellation

Two rows deserve emphasis. A signal gives consumers only the latest value: if you set it three times in a row, an effect that reads it runs once and sees the third. An observable delivers all three. That is a feature in both cases, but it means converting between them is not lossless. The second is cleanup: a subscription that nobody unsubscribes from is a memory leak, while signals clean up with their owner.

flowchart LR
  O["Observable<br/>(events over time)"] -- "toSignal()" --> S["Signal<br/>(current state)"]
  S -- "toObservable()" --> O
  S --> T["Template"]
  O -- "operators:<br/>debounceTime, switchMap, retry" --> O

Use observables for the stream-shaped work, then land the result in a signal for the template to read.

toSignal: from observable to signal

toSignal subscribes to an observable and exposes its latest value as a read-only signal. It subscribes right away and unsubscribes automatically when the surrounding component (or other injection context) is destroyed.

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

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

@Component({
  selector: 'app-courses',
  template: `
    @for (course of courses(); track course.id) {
      <p>{{ course.title }}</p>
    } @empty {
      <p>Nothing yet</p>
    }
  `,
})
export class CoursesComponent {
  private readonly http = inject(HttpClient);

  readonly courses = toSignal(this.http.get<Course[]>('/api/courses'), {
    initialValue: [],
  });
}

A signal must always have a value, but an observable may not have emitted yet. There are three ways to resolve that gap:

  • initialValue supplies the value to show until the first emission, as above. The signal's type is then just Course[].
  • No initialValue gives a signal of Course[] | undefined. The undefined means "not loaded yet", and your template has to handle it.
  • requireSync: true tells Angular the observable emits synchronously on subscribe (a BehaviorSubject or of(...) does). The type has no undefined, and Angular throws if it turns out not to be synchronous.

Some behaviors to know:

  • It must run in an injection context (a field initializer, a constructor, or inside runInInjectionContext). Calling toSignal later from a click handler throws, because Angular cannot find the owner whose destruction ends the subscription. Pass { injector } if you really must create one late.
  • Errors resurface on read. If the observable errors, reading the signal throws that error. Handle failure inside the observable (catchError) if you want the signal to show a fallback.
  • It subscribes once. Each toSignal call is a subscription. For a cold observable such as http.get, that means one request, made when the component is created, whether or not the template ever reads the signal.
  • A completed observable keeps its last value.

Do not call toSignal inside a computed signal, an effect or a method that runs repeatedly. Every call creates a new subscription (and, with HTTP, a new request). Create it once, as a field, and read the resulting signal wherever you need it.

toObservable: from signal to observable

The opposite bridge turns a signal into an observable so you can apply operators to it. This is the standard way to add debounceTime or switchMap to something driven by user input held in a signal:

TypeScript
import { Component, inject, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';

@Component({
  selector: 'app-search',
  template: `
    <input [value]="query()" (input)="query.set($any($event.target).value)" />
    @for (hit of results(); track hit) {
      <p>{{ hit }}</p>
    }
  `,
})
export class SearchComponent {
  private readonly api = inject(SearchApi);

  readonly query = signal('');

  readonly results = toSignal(
    toObservable(this.query).pipe(
      debounceTime(300),
      distinctUntilChanged(),
      switchMap((q) => this.api.search(q)),
    ),
    { initialValue: [] as string[] },
  );
}

Signal in, operators in the middle, signal out. The state lives in signals, and the observable pipeline only handles the time-based part. switchMap also cancels an in-flight request when a newer query arrives, which a plain signal cannot express.

toObservable uses an effect internally, which has an important consequence: emissions are asynchronous and batched. If the signal changes three times before Angular next runs its effects, the observable emits only the final value. That is usually what you want for state (nobody needs the stale intermediate query), but do not use toObservable for something where every set must be seen, such as a log of actions. Use a Subject for that.

takeUntilDestroyed and outputFromObservable

Not every subscription becomes a signal. Sometimes you subscribe for a side effect: write to a log, call a service. In that case, tie the subscription to the component's life with takeUntilDestroyed, so it ends automatically:

TypeScript
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';

@Component({ selector: 'app-ticker', template: '' })
export class TickerComponent {
  private readonly destroyRef = inject(DestroyRef);

  constructor() {
    // In a constructor or field initializer: no argument needed
    interval(1000).pipe(takeUntilDestroyed()).subscribe((n) => console.log(n));
  }

  startLater(): void {
    // Outside an injection context: pass the DestroyRef yourself
    interval(500).pipe(takeUntilDestroyed(this.destroyRef)).subscribe();
  }
}

Without an argument, takeUntilDestroyed() must be called in an injection context, like toSignal. Place it last in the pipe, so that operators before it don't keep a subscription alive that it could not clean up.

A component's output is normally created with output() and fired with emit. If the event already exists as an observable, outputFromObservable creates the output directly from it, and outputToObservable goes the other way, so a parent can use operators on a child's output:

TypeScript
import { Component } from '@angular/core';
import { outputFromObservable } from '@angular/core/rxjs-interop';
import { Subject, debounceTime } from 'rxjs';

@Component({
  selector: 'app-filter-box',
  template: `<input (input)="typed.next($any($event.target).value)" />`,
})
export class FilterBoxComponent {
  protected readonly typed = new Subject<string>();

  // The parent listens with (changed)="..."; it fires 250 ms after typing stops
  readonly changed = outputFromObservable(this.typed.pipe(debounceTime(250)));
}

async pipe or toSignal?

Both subscribe to an observable and show its value in a template. The async pipe ({{ data$ | async }}) subscribes where it is written and unsubscribes when the view goes away. toSignal subscribes in the class and gives you a value you can also use in TypeScript, in computed, and in other templates.

Reach for toSignal in new code: the value is available in the class, it composes with computed, and there is a single subscription however many times you read it. With the async pipe, every | async in a template is its own subscription, which for a cold observable means several HTTP requests unless you share it. The pipe is still fine in older or template-only code and is not deprecated.

A practical rule for choosing:

  • Holding state the template shows? Signal.
  • Combining it with other state? computed.
  • Reacting to an event stream, debouncing, cancelling, retrying? Observable operators.
  • Observable result needed in the template? toSignal.
  • Signal input to an operator pipeline? toObservable.
  • Subscribing only for a side effect? takeUntilDestroyed.

Resist converting everything. A signal that goes into toObservable and straight back through toSignal with a single map is better written as a computed.

A runnable toSignal stand-in

This stand-in has a tiny Subject, a DestroyRef that runs callbacks on destroy, and a toSignal that subscribes immediately, starts from an initial value and unsubscribes when its owner is destroyed. Watch what the signal shows before the first emission and after destruction.

TypeScript Stand-in: toSignal with an initial value and cleanup

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.

The real toSignal returns a true signal, so templates and computed re-run when the value changes; this stand-in returns a plain getter, which is enough to show the three ideas. The initial value covers the gap, the subscription starts at once, and destroying the owner ends it, so the subject has no leaked listener.

A runnable toObservable stand-in

Now the opposite direction. This signal notifies listeners when it changes, and toObservable delivers the signal's current value in a microtask, so several quick changes collapse into one emission. A Subject receives every set call for comparison.

TypeScript Stand-in: toObservable batches changes, a Subject does not

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.

The first three set calls happen before the microtask runs, so the observable reports only 3; the intermediate 1 and 2 are lost, just as a real effect would skip them. Changes separated by a tick are each delivered. If your logic needs every event, an observable (a Subject) is the right source, not a signal.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does toSignal need when the observable has not emitted yet and you want a signal without undefined in its type?

    A signal always has a value. initialValue provides one until the first emission; requireSync is for observables that emit synchronously on subscribe. Otherwise the type includes undefined.
  2. 2. You write count.set(1); count.set(2); count.set(3) in one handler. How many values does toObservable(count) emit for them?

    toObservable is driven by an effect, which runs once with the latest value. Intermediate values are skipped. Use a Subject if every event matters.
  3. 3. Why is it a mistake to call toSignal inside a click handler?

    toSignal needs an injection context to know when to unsubscribe, and repeated calls would pile up subscriptions (and repeat HTTP requests). Create it once as a field.
  4. 4. Where should takeUntilDestroyed() go in a pipe?

    Put it last so that every operator before it is unsubscribed when the component is destroyed, avoiding leaks from operators placed after it.
  5. 5. Which tool fits the job: wait 300 ms after the user stops typing, cancel the old request, then show the results in a template?

    Time-based and cancellation work is what RxJS operators are for. Bridge the input signal into an observable, pipe the operators, and bring the result back with toSignal.

Summary

  • Signals hold state and are read synchronously; observables describe events over time. Use each for what it is best at and bridge them with @angular/core/rxjs-interop.
  • toSignal(obs$, { initialValue }) subscribes once, cleans up automatically and needs an injection context. Without an initial value, the type includes undefined; requireSync is for synchronous sources. Errors are thrown when you read the signal.
  • toObservable(signal) emits asynchronously and batches rapid changes into the latest value.
  • takeUntilDestroyed() ends a subscription with the component; put it last in the pipe.
  • outputFromObservable and outputToObservable connect component outputs with streams.
  • Prefer toSignal over the async pipe in new code, and do not convert back and forth when a computed would do.
  • The Angular code in this lesson is read-only; the bridges shown are simplified stand-ins.

Next: Testing Components and Services