Angular Map Operator: Usage and Examples

The Angular observable Map operator takes an observable source as input. It applies a project function to each of the values emitted by the source observable and transforms them into a new value. It then emits the new value to the subscribers. We use an angular map operator with a Pipe, which allows us to chain multiple operators together. In this guide, we’re going to learn how to use the Map operator with examples like converting the source to upper case, using Map with the Angular HTTP Request, with DOM events, filtering the input data, and using multiple Map Operators together, etc.

Syntax

The syntax of the map operator is as follows:

project: is a function that we use to manipulate the values emitted by the source observable. The project can accept two arguments. One is value i.e., the value emitted by the observable. The second argument is the index number. The index number starts with 0 for the first value emitted and is incremented by one for every subsequent value emitted. It is similar to the index of an array.

thisArg: is optional and default is undefined. It defines what this is in the project function.

Using Observable Map

To use map first, we need to import it from the rxjs/operators library.

Next, create an observable from an array of numbers as shown below.

Use the pipe method to invoke the map method.

The project function accepts only one argument val and returns it multiplied by 2.

Finally, we subscribe and print the result in the console. The output is 2,4,6,8

The following image explains how values from the source observable ( i.e.1,2,3,4 ) go through the map which transforms it into new values by multiplying it by 2.

You can also access the second argument index as shown below. It starts as 0 for the first value and gets incremented for every subsequent value.

Map Examples

Convert input to upper-case

Map to a Single Property

Using Map with HTTP Request

The following code gets the list of dogs breeds from the https://dog.ceo/api/breeds/list/all API and uses the keyValue pipe to transform the object into an array of key-value pairs.

Using with event

You can create observable from event and use the map to transform the values.

map with filter

Multiple map

The following examples show the use of multiple map functions. The first map adds 10, while the second mad multiplies by 2.

References

  1. Map API

3 thoughts on “Angular Map Operator: Usage and Examples”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top