Observables and RxJS Basics

An observable is a stream of values that arrive over time. Nothing happens until you subscribe, with handlers for the values, an error and the end. HttpClient's observables send one value, the response, then complete. RxJS operators in pipe, such as map, transform the values.

Journeyman · Angular · Updated

After this lesson you can

  • Subscribe to an observable with handlers for its values and its errors
  • Transform an observable's values with pipe and map

Key takeaways

  • An observable is a stream of values over time: subscribe with next for each value, error for a failure and complete for the end.
  • An observable is lazy: nothing is sent until you subscribe, and subscribing twice calls the API twice.
  • An HttpClient observable sends one value, the response's body, then completes. Any status that isn't 2xx, such as 404, arrives in error.
  • Operators go in pipe(...), and RxJS's map changes each value, like LINQ's Select.
  • Stop an endless stream, such as interval, with unsubscribe() in ngOnDestroy; HttpClient's observables complete by themselves.

HttpClient returns observables, from a library called RxJS that comes with Angular. Observables are a bigger idea than promises, and you'll meet them all over Angular.

A stream of values

A promise delivers one value, later. An observable delivers any number of values, over time: a stream. Think of the difference between ordering a pizza (one delivery) and subscribing to a magazine (one every month, until you cancel).

import { interval, take } from 'rxjs';

const ticks = interval(1000).pipe(take(3));

ticks.subscribe({
  next: value => console.log(`tick ${value}`),
  complete: () => console.log('done'),
});
tick 0
tick 1
tick 2
done
  • interval(1000) is an observable that sends 0, 1, 2, … one a second, forever.
  • take(3) lets the first three through, then ends the stream.
  • subscribe starts listening, with handlers for each kind of message:
Handler Called
next For each value
error If something goes wrong; the stream ends
complete When the stream ends normally

subscribe(value => ...) with just a function is short for { next: value => ... }.

Nothing happens until you subscribe

An observable is lazy: it's a recipe, like a LINQ query. http.get(...) doesn't send anything. The request goes when you subscribe, and if you subscribe twice, it's sent twice. So: forget to subscribe, and nothing happens; subscribe in two places, and the API is called twice.

HttpClient's observables

An HttpClient observable is simple: it sends one value, the response's body, then completes. Or, if the request fails, it sends an error instead:

this.api.getById(300).subscribe({
  next: category => this.category.set(category),
  error: (error: HttpErrorResponse) => this.message.set(`Couldn't load category 300 (${error.status})`),
});

The API answers 404, so error runs, with an HttpErrorResponse (from @angular/common/http) whose status is 404. Unlike fetch, HttpClient treats every status that isn't 2xx as an error, so a missing item, a validation 400 and a 500 all arrive in error.

pipe and map

Operators transform a stream as it flows, like LINQ's methods. Put them in pipe(...); each one passes on a new stream. The most useful is map, RxJS's Select: it changes each value.

import { map } from 'rxjs';

getNames(): Observable<string[]> {
  return this.http.get<Category[]>('/api/categories').pipe(
    map(categories => categories.map(category => category.categoryName))
  );
}

There are two maps here: RxJS's map changes the stream's value (the list of categories becomes a list of names), and the array's map does the work on the list. Subscribers to getNames() get ['Beverages', 'Condiments', …].

A few more operators you'll meet:

Operator Does Like
map(x => ...) Changes each value LINQ Select
filter(x => ...) Lets through only some values LINQ Where
take(n) Takes the first n values, then ends LINQ Take
catchError(e => ...) Replaces an error with something else, such as an empty list catch

Stopping a subscription

A subscription to an endless stream, such as interval, keeps running until it's stopped. subscribe returns a Subscription; call unsubscribe() on it, in ngOnDestroy, to stop it. HttpClient's observables complete by themselves after one value, so you don't need to unsubscribe from them; the next lesson shows a way that unsubscribes for you anyway.

Check yourself

2 questions to try on the lesson page.

So what

An observable is a stream you subscribe to: next for values, error for failures, complete for the end. HttpClient sends one value or an error, and pipe with operators like map shapes the data before your component sees it.

Key terms

Cheat sheets