Sub topic 8
Showing API Data in Components
The data service from earlier chapters returns Observables. A component still has to subscribe to them, keep the latest value, render it, and stop listening when the component is destroyed. This chapter compares the three usual ways to do that: the async pipe, toSignal, and a manual subscribe. It also covers the loading and error states a real screen needs.
The chapter assumes you know Angular standalone components and the built-in control flow blocks (@if, @for). It also assumes you have the TodoService and Todo interface from the earlier chapters, and that you know Observables are lazy: nothing happens until something subscribes.
The Three Ways to Consume an Observable
All three approaches subscribe to the same HttpClient Observable. They differ in who owns the subscription and where the value lives.
| Approach | Who subscribes | Who unsubscribes | Value lives in | Best fit |
|---|---|---|---|---|
| `async` pipe | The template | The pipe, when the view is destroyed | The template only | Templates that only display the data |
| `toSignal` | `toSignal`, at creation | `toSignal`, through `DestroyRef` | A read-only signal | Signal-based components, `computed` values |
| Manual `subscribe` | Your code | Your code (`takeUntilDestroyed`) | A field or writable signal | When you also need side effects or local edits |
An HTTP Observable emits one response and then completes, so a forgotten subscription will not leak forever. Unsubscribing still matters. If the user leaves the page while the request is in flight, unsubscribing cancels the request. It also stops the callback from writing to a component that no longer exists.
The async Pipe
The async pipe subscribes when the view renders the expression and unsubscribes when the view is destroyed. Before the first value arrives it returns null.
// todo-list-async.component.ts
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable } from 'rxjs';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-todo-list-async',
standalone: true,
imports: [AsyncPipe],
template: `
@if (todos$ | async; as todos) {
<ul>
@for (todo of todos; track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li>No todos yet.</li>
}
</ul>
} @else {
<p>Loading…</p>
}
`
})
export class TodoListAsyncComponent {
private readonly todoService = inject(TodoService);
readonly todos$: Observable<Todo[]> = this.todoService.getTodos(1);
}The as todos alias stores the emitted value in a template variable, so the template subscribes once. The @else branch shows while the pipe still returns null.
One edge case: if the API can return a falsy body such as 0, '' or false, @if (x$ | async; as x) treats it like "still loading". An empty array [] is truthy, so lists are fine.
toSignal
toSignal from @angular/core/rxjs-interop subscribes right away and exposes the latest value as a signal. It unsubscribes when the component's DestroyRef fires.
// todo-list.component.ts
import { Component, computed, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { TodoService } from './todo.service';
@Component({
selector: 'app-todo-list',
standalone: true,
template: `
<p>{{ openCount() }} open</p>
<ul>
@for (todo of todos(); track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li>No todos yet.</li>
}
</ul>
`
})
export class TodoListComponent {
private readonly todoService = inject(TodoService);
readonly todos = toSignal(this.todoService.getTodos(1), { initialValue: [] });
readonly openCount = computed(() => this.todos().filter(t => !t.completed).length);
}The benefit over the async pipe is that the value is now usable in TypeScript. computed derives openCount from it, and the template reads todos() as many times as it likes without creating extra subscriptions. toSignal subscribes exactly once.
The initialValue option sets the signal's type and its starting value:
| Option | Signal type | Value before the response arrives | Column |
|---|---|---|---|
| none | `Signal<Todo[] \ | undefined>` | `undefined` |
| `initialValue: []` | `Signal<Todo[]>` | `[]` | |
| `requireSync: true` | `Signal<Todo[]>` | Throws unless the source emits synchronously |
requireSync does not work on a bare HTTP Observable, because the response always arrives asynchronously. It becomes useful once you add a synchronous starting value with startWith, as the next section shows.
Injection Context Gotcha
toSignal needs an injection context to find DestroyRef. Field initializers and the constructor have one. ngOnInit and event handlers do not, and calling toSignal there throws error NG0203. If you must create the signal later, pass an injector:
import { Component, Injector, OnInit, Signal, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-late-todos',
standalone: true,
template: `<p>{{ todos().length }} todos</p>`
})
export class LateTodosComponent implements OnInit {
private readonly injector = inject(Injector);
private readonly todoService = inject(TodoService);
todos!: Signal<Todo[]>;
ngOnInit(): void {
this.todos = toSignal(this.todoService.getTodos(1), {
initialValue: [],
injector: this.injector
});
}
}Errors Inside a Signal
If the source Observable errors, toSignal stores the error and rethrows it every time the signal is read. A template reading todos() will then throw during rendering. Handle the error in the Observable pipeline before it reaches toSignal, which the next section does.
Modelling Loading and Error States
A real screen shows three states: loading, loaded, and failed. A discriminated union models this cleanly. You map the HTTP stream into it so the component never sees a raw error.
// todo-page.component.ts
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, map, of, startWith } from 'rxjs';
import { Todo, TodoService } from './todo.service';
type LoadState<T> =
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };
@Component({
selector: 'app-todo-page',
standalone: true,
template: `
@if (state(); as s) {
@if (s.status === 'loading') {
<p>Loading…</p>
} @else if (s.status === 'error') {
<p role="alert">{{ s.message }}</p>
} @else {
<ul>
@for (todo of s.data; track todo.id) {
<li>{{ todo.title }}</li>
} @empty {
<li>No todos yet.</li>
}
</ul>
}
}
`
})
export class TodoPageComponent {
private readonly todoService = inject(TodoService);
readonly state = toSignal(
this.todoService.getTodos(1).pipe(
map((data): LoadState<Todo[]> => ({ status: 'success', data })),
catchError(() =>
of<LoadState<Todo[]>>({ status: 'error', message: 'Could not load todos.' })
),
startWith<LoadState<Todo[]>>({ status: 'loading' })
),
{ requireSync: true }
);
}The order of the operators matters:
mapwraps a successful body.catchErrorturns a failure into an error state, so the stream completes normally andtoSignalnever stores an exception.startWithemitsloadingsynchronously on subscribe. That is whyrequireSync: trueis valid, and why the signal type has noundefined.
With strictTemplates enabled, the s.status === 'error' check narrows s, so s.message and s.data are type-checked. The @if (state(); as s) alias is needed because Angular cannot narrow repeated state() calls.
Manual subscribe with takeUntilDestroyed
Subscribe yourself when the response feeds state you will also change locally. One example is a list you append to after a POST.
// editable-todos.component.ts
import { Component, inject, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Todo, TodoService } from './todo.service';
@Component({
selector: 'app-editable-todos',
standalone: true,
template: `
<button (click)="add()">Add todo</button>
<ul>
@for (todo of todos(); track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
`
})
export class EditableTodosComponent {
private readonly todoService = inject(TodoService);
readonly todos = signal<Todo[]>([]);
constructor() {
this.todoService.getTodos(1)
.pipe(takeUntilDestroyed())
.subscribe(todos => this.todos.set(todos));
}
add(): void {
this.todoService.addTodo('New todo')
.subscribe(created => this.todos.update(list => [...list, created]));
}
}takeUntilDestroyed() with no argument also needs an injection context, so it sits in the constructor. The add() handler skips it: a single POST completes by itself, and cancelling a write halfway because the user navigated away is usually not what you want.
Sharing One Request Between Consumers
If several places need the same response, such as two components or two async pipes, share the Observable so only one request goes out:
import { shareReplay } from 'rxjs';
// Inside a component or service
readonly todos$ = this.todoService.getTodos(1).pipe(
shareReplay({ bufferSize: 1, refCount: true })
);bufferSize: 1 replays the last response to late subscribers. refCount: true drops the shared subscription when the last subscriber leaves, so a later subscriber triggers a fresh request rather than getting a stale cached value forever. With toSignal you rarely need this, because one signal already serves every reader.
Common Mistakes
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| Two identical requests in the Network tab | Two `\ | async` on one Observable | Use one `as` alias, `toSignal`, or `shareReplay` |
| `NG0203` error | `toSignal` or `takeUntilDestroyed()` called in `ngOnInit` | Move it to a field initializer or pass `injector` / `DestroyRef` | |
| Template crashes after an API failure | `toSignal` rethrows the stored error on read | Use `catchError` in the pipe before `toSignal` | |
| No request is sent at all | The Observable was created but never subscribed | Bind it with `async`, wrap it in `toSignal`, or subscribe | |
| Type errors about `undefined` | `toSignal` without `initialValue` | Add `initialValue` or handle `undefined` in the template |
Exercise
A template contains <h2>{{ (todos$ | async)?.length }} todos</h2> and, further down, @for (todo of (todos$ | async) ?? []; track todo.id). How many GET requests does this send, and what are two ways to reduce it to one?
Show answer
Two requests, because each async pipe subscribes separately to the cold HttpClient Observable. One fix is to wrap the whole block in @if (todos$ | async; as todos) and use todos in both places. Another is to replace the Observable with todos = toSignal(..., { initialValue: [] }) and read todos() twice. Adding shareReplay({ bufferSize: 1, refCount: true }) to todos$ also works.
Exercise
A developer writes readonly todos = toSignal(this.todoService.getTodos(1)); and the server returns 500. What happens when the template reads todos(), and how should the code change?
Show answer
toSignal stores the HttpErrorResponse and rethrows it on every read, so rendering the template throws. Add catchError inside the pipe before toSignal, either returning a fallback such as of([]) or mapping to an error state like the LoadState union, so the signal always holds a value.
Exercise
Why can requireSync: true be used in TodoPageComponent but not with toSignal(this.todoService.getTodos(1), { requireSync: true })?
Show answer
requireSync demands that the Observable emit synchronously during subscription. A bare HTTP request emits only after the network response arrives, so toSignal would throw. In TodoPageComponent, startWith({ status: 'loading' }) emits synchronously on subscribe, which satisfies the requirement.