Using Map operator in Angular

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 it into a new value. It then emits the new value to the subscribers. We use a Map 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 the Angular HTTP Request, with DOM events, filtering the input data, and using multiple Maps 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 index number. The index number starts from 0 for the first value emitted and 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 array of numbers as shown below.

Use the pipe method to and 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 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.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

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 shows use of multiple map functions. The first map adds 10, while the second mad multiplies by 2.

References

  1. Map API

Leave a Comment

Your email address will not be published.

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

Scroll to Top