Higher-Order Observables
Learn how to use higher-order observables in Angular, emphasizing the switchMap and mergeMap operators.
We'll cover the following
Observables that operate on other observables of observables are called higher-order observables. Higher-order observables have an inner observable that contains the actual values we are interested in using. We can use specific RxJS operators to flatten the inner observable and extract its values. The most used flattened operators in Angular development are the switchMap
and mergeMap
operators.
The switchMap
operator
The switchMap
operator takes an observable as a source and applies a given function to each item, returning an inner observable for each one. The operator returns an output observable with values emitted from each inner observable. As soon as an inner observable emits a new value, the output observable stops receiving values from the other inner observables.
We will now investigate how switchMap
is usually used in Angular applications. Recall the ProductsService
and ProductViewService
classes studied previously. We will now convert them to use observables instead of plain arrays and learn how to combine them using the switchMap
operator.
Note: In this chapter, we will work with the product list and product view components for simplicity and repeatability. However, the
products
module also contains other components and services that must be modified to reflect the use of observables in the codebase. The source code section has been trimmed down to compile successfully without those components and services.
Open the
products.service.ts
file and import theof
andObservable
artifacts from therxjs
npm package:
Get hands-on with 1200+ tech skills courses.