Sub topic 8
Showing API Data in Components
This chapter assumes you already have a TodoService whose getTodos(page) method returns Observable<Todo[]>. It also assumes you know standalone components and the built-in @if and @for control flow blocks. The question here is how a component reads that Observable and renders the data without leaking subscriptions.
The Problem with Manual Subscriptions
An HttpClient Observable does nothing until something subscribes to it. You could call .subscribe() in ngOnInit and copy the result into a field. That approach comes with chores: you store the data yourself, you remember to unsubscribe if the component is destroyed before the response arrives, and you trigger change detection correctly. Angular offers two tools that handle all of this for you.
| Approach | Where it subscribes | Cleanup | Value type in template | Column |
|---|---|---|---|---|
| `async` pipe | In the template | Automatic when the view is destroyed | `T \ | null` |
| `toSignal` | In the component class | Automatic when the injection context is destroyed | `Signal<T>` (or `T \ | undefined` without `initialValue`) |
Option 1: The async Pipe
The async pipe subscribes when the template renders. It returns the latest emitted value and unsubscribes when the view goes away.
// todo-list-async.component.ts
import { Component, inject } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { 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$ = this.todoService.getTodos(1);
}The as todos alias matters. HttpClient Observables are cold, which means every subscription sends its own request. If you wrote todos$ | async in three places, the browser would make three identical requests. Bind the pipe once and reuse the alias.
Option 2: toSignal
toSignal from @angular/core/rxjs-interop subscribes right away and exposes the latest value as a signal. Templates read signals by calling them, and they fit with computed for derived state.
// 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 signal subscribes once, so reading todos() several times does not send extra requests.
How the Lifecycle Fits Together
Choosing Between Them
Use the async pipe when the data is only displayed and your codebase is built around Observables. Use toSignal when you want to derive values with computed, read the data in class code, or work with signal-based inputs. Both remove manual subscription handling. The main mistakes to avoid are duplicate async subscriptions and calling toSignal outside an injection context.
Exercise
A template contains {{ (todos$ | async)?.length }} in a header and @for (todo of (todos$ | async); track todo.id) in a list. How many HTTP requests are sent, and how would you fix it?
Show answer
Two requests are sent, because each async pipe subscribes separately to the cold HttpClient Observable. To fix it, wrap the section in @if (todos$ | async; as todos) and use todos in both places, or convert the Observable once with toSignal and read todos().
Exercise
Why does this.todos = toSignal(this.todoService.getTodos(1)) fail when placed inside ngOnInit, and what are two ways to fix it?
Show answer
toSignal needs an injection context so it can register cleanup when the component is destroyed, and ngOnInit does not run in one. Either move the call into a field initializer or the constructor, or inject Injector and pass it as toSignal(obs$, { injector: this.injector }).