Sub topic 10
Understanding Observables and RxJS basics
This chapter explains what an Observable is, how it differs from a Promise and from a signal, and which RxJS pieces you need before the next chapter uses HttpClient. It assumes you know the following:
- TypeScript generics and arrow functions.
- Promises and
async/await. - The
TaskServiceand signals from the earlier chapters.
You do not need prior RxJS experience.
What an Observable is
An Observable is an object that describes a stream of values over time. It does not hold a value. It holds a recipe for producing values, and the recipe runs only when someone subscribes.
A subscriber can receive three kinds of notification:
next: a value arrived. This can happen zero, one, or many times.error: something failed. The stream ends and no more values arrive.complete: the stream finished normally. No more values arrive.
A stream ends with either error or complete, never both. Many streams, such as a click stream, never end on their own.
RxJS is the library that provides Observables and the tools to transform them. Angular depends on it, so it is already installed in your project. By convention, variables that hold Observables end in $, for example tasks$.
Observables are lazy
Creating an Observable does not run anything. The function you pass to the constructor runs once per subscription.
import { Observable } from 'rxjs';
const numbers$ = new Observable<number>(subscriber => {
console.log('producer started');
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
return () => console.log('teardown');
});
console.log('before subscribe');
numbers$.subscribe({
next: value => console.log('got', value),
error: err => console.error('failed', err),
complete: () => console.log('done'),
});
numbers$.subscribe(value => console.log('second subscriber got', value));The output is:
before subscribe
producer started
got 1
got 2
done
teardown
producer started
second subscriber got 1
second subscriber got 2
teardownThree things to notice:
- "producer started" appears after "before subscribe", because nothing ran until
subscribe. - The producer ran twice, once for each subscriber. This is called a cold Observable: every subscriber gets its own execution.
- The function you return from the producer is the teardown. RxJS calls it when the stream completes, errors, or the subscriber unsubscribes. It is where you release resources such as timers or event listeners.
How this differs from a Promise
| Aspect | Promise | Observable |
|---|---|---|
| Starts running | Immediately on creation | On `subscribe` |
| Values | Exactly one | Zero, one, or many |
| Re-running | Never, the result is cached | Each subscription runs the producer again (cold) |
| Cancellation | Not built in | Unsubscribe triggers teardown |
| Transformation | `.then` chains | Operators in `pipe` |
The "re-running" row causes the most surprises in Angular. If you subscribe twice to this.http.get(...), the browser sends two requests.
Transforming streams with operators and pipe
An operator is a function that takes an Observable and returns a new one. You chain operators with pipe. The original Observable is never modified.
import { of } from 'rxjs';
import { filter, map, tap } from 'rxjs/operators';
interface Task {
id: number;
title: string;
done: boolean;
}
const tasks: Task[] = [
{ id: 1, title: 'Write tests', done: true },
{ id: 2, title: 'Add routing', done: false },
{ id: 3, title: 'Build for production', done: false },
];
of(...tasks)
.pipe(
filter(task => !task.done),
tap(task => console.log('passing through', task.id)),
map(task => task.title.toUpperCase()),
)
.subscribe(title => console.log(title));of(...tasks) emits each task in turn and then completes. The output is:
passing through 2
ADD ROUTING
passing through 3
BUILD FOR PRODUCTIONEach value travels through the whole pipeline before the next value starts. That is why the log lines alternate.
These are the operators you will meet most often in Angular code:
| Operator | What it does |
|---|---|
| `map` | Transforms each value |
| `filter` | Passes only values that match a condition |
| `tap` | Runs a side effect, such as logging, and passes the value on unchanged |
| `catchError` | Replaces an error with a fallback Observable |
| `switchMap` | For each value, starts an inner Observable and cancels the previous inner one |
| `takeUntilDestroyed` | Completes the stream when the component or service is destroyed |
You can import all of them from 'rxjs' in current RxJS versions. The 'rxjs/operators' path also still works.
Handling errors
An error ends the stream. If you do not handle it in subscribe or with catchError, RxJS reports it as an unhandled error.
catchError receives the error and must return a new Observable to continue with. This is how you turn a failed request into a harmless fallback.
import { of, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
throwError(() => new Error('network down'))
.pipe(
map(() => 'never reached'),
catchError(err => {
console.warn('recovering from', err.message);
return of('fallback value');
}),
)
.subscribe(value => console.log(value));throwError takes a factory function, not an error object. The output is "recovering from network down" followed by "fallback value".
Using Observables in the task list app
The TaskApi service from the HTTP chapter returns Observable<Task[]>. The simplest way to show that data in a signal-based component is toSignal, from @angular/core/rxjs-interop. It subscribes for you, stores the latest value in a signal, and unsubscribes when the component is destroyed.
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { catchError, of } from 'rxjs';
import { Task } from './task';
import { TaskApi } from './task-api';
@Component({
selector: 'app-remote-tasks',
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks loaded.</li>
}
</ul>
`,
})
export class RemoteTasksComponent {
private readonly api = inject(TaskApi);
readonly tasks = toSignal(
this.api.getTasks().pipe(catchError(() => of([] as Task[]))),
{ initialValue: [] as Task[] },
);
}This example assumes the TaskApi class from the earlier code lives in task-api.ts. Adjust the import path to match your file name.
Points to check:
initialValuegives the signal a value before the first emission. Without it, the signal type isTask[] | undefined.toSignalmust run in an injection context, such as a field initializer or a constructor. Calling it inside a click handler throws an error.catchErrorkeeps a failed request from throwing inside the signal. The component shows the empty state instead.
Unsubscribing
If you call subscribe yourself, you own the subscription. A stream that never completes, such as interval or a DOM event stream, keeps running after the component is gone unless you stop it.
import { Component } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({
selector: 'app-ticker',
template: `<p>Open the console to see ticks.</p>`,
})
export class TickerComponent {
constructor() {
interval(1000)
.pipe(takeUntilDestroyed())
.subscribe(count => console.log('tick', count));
}
}takeUntilDestroyed() called without arguments works only in an injection context. Outside one, pass a DestroyRef instead: takeUntilDestroyed(this.destroyRef).
Observables versus signals
Both hold changing data, but they answer different questions.
| Aspect | Signal | Observable |
|---|---|---|
| Has a current value | Always | Not necessarily |
| Read it | Call it: `tasks()` | Subscribe |
| Best for | State the template displays | Events and asynchronous work over time |
| Cancellation | Not applicable | Unsubscribe |
A practical rule for this app: keep state in signals, and use Observables for things that happen over time, such as HTTP calls. Use toSignal to move from an Observable into a signal when the template needs the result.
Common mistakes
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| Nothing happens and no request is sent | The Observable was never subscribed to | Call `subscribe`, use `toSignal`, or use the `async` pipe | |
| Two identical requests in the network tab | The same cold Observable was subscribed to twice | Subscribe once and share the result, for example through a signal | |
| Handlers keep firing after navigating away | A long-lived subscription was not cleaned up | Add `takeUntilDestroyed()` | |
| `toSignal` throws about injection context | It was called outside a constructor or field initializer | Move the call, or pass an `Injector` in its options | |
| The stream stops after one failure | The error was not caught, or `catchError` was placed outside an inner Observable | Handle the error with `catchError` before it ends the stream | |
| Type is `Task[] \ | undefined` | `toSignal` was used without `initialValue` | Provide `initialValue` |
Exercise
A teammate writes const request$ = this.api.getTasks(); in a component and sees no network request. Then they add request$.subscribe(); request$.subscribe(); and see two requests. Explain both observations.
Show answer
Observables are lazy. Creating request$ only describes the call, so no request is sent until a subscription happens. HttpClient Observables are cold, so each subscribe runs the producer again and sends its own request. Subscribe once, or convert the result to a signal with toSignal so there is a single subscription.
Exercise
What does this code log, and in what order? of(1, 2, 3, 4).pipe(filter(n => n % 2 === 0), map(n => n * 10)).subscribe({ next: v => console.log(v), complete: () => console.log('done') });
Show answer
It logs 20, then 40, then done. The filter operator keeps only 2 and 4, map multiplies each by 10, and of completes after emitting its last value, which triggers the complete callback.
Exercise
Write the toSignal call that turns this.api.getTasks() into a signal of Task[], shows an empty array before data arrives, and shows an empty array if the request fails.
Show answer
readonly tasks = toSignal(this.api.getTasks().pipe(catchError(() => of([] as Task[]))), { initialValue: [] as Task[] }); The initialValue covers the time before the first emission, and catchError replaces an error with an Observable that emits an empty array.