AI Hints
Home›Angular Tutorial›toSignal(), Why Test and Testing a Component
Angular · Lesson 103 of 120

toSignal()

Observables to signals.

⏱ 2 min read▶ Video at 2:04:28🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Our templates love signals. RxJS gives us observables. Angular has two small functions, that convert between them.

  • Templates love signals
  • RxJS gives observables
  • Convert between them

toSignal and toObservable

To signal subscribes to an observable, and keeps its latest value in a signal. It also unsubscribes for us, when the component is destroyed. Initial value is used until the first value arrives. To observable goes the other way.

keyvalue
toSignal(obs$, { initialValue })observable → signal
Unsubscribesautomatically
initialValuebefore the first value
toObservable(sig)signal → observable

The input is a form control. Its value changes stream goes through debounce time, then switch map, which calls the search. To signal turns the results into a signal, starting with an empty list. And the template reads it, like any signal. We type austen. Run it. Only one request reached the server, after we stopped typing. And it found Emma.

app.tstypescript
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
import { debounceTime, switchMap } from 'rxjs';
import { BookApi } from './book-api';
@Component({
  selector: 'app-root', imports: [ReactiveFormsModule],
  template: `
    <input [formControl]="search" placeholder="Search">
    @for (b of results(); track b.id) { <p>{{ b.title }} · {{ b.author }}</p> }
  `,
})
export class App {
  private api = inject(BookApi);
  search = new FormControl('', { nonNullable: true });
  results = toSignal(this.search.valueChanges.pipe(debounceTime(300),
    switchMap(q => this.api.search(q))), { initialValue: [] });
}
Output
API GET /api/books?q=austen → 200
Also uses book-api.ts
import { Service, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';

export interface Book { id: number; title: string; author: string; price: number; }

@Service()
export class BookApi {
  private http = inject(HttpClient);

  search(q: string) {
    return this.http.get<Book[]>(`/api/books?q=${q}`);
  }
}
Also uses actions.json
[{"type": "input", "text": "austen"}, {"wait": 1000}]
Also uses _apilog
1

Summary

To signal turns an observable into a signal, and cleans up for us. Now our search waits for the user, and sends one request. Next, testing.

Key takeaways
  • toSignal()
  • initialValue
  • toObservable()
Next up: Why Test — catch mistakes early