Map Operator In Angular

Map Operator In Angular

An observable source is used as the input for the Angular observable Map operator. It turns each of the values emitted by the source observable into a new value using a project function. The revised value is then sent to the subscribers. We use a Map in conjunction with a Pipe to link numerous operators together. In this article, we will learn how to use the Map operator with examples such as changing the source to upper case, using Map with the Angular HTTP Request, with DOM events, filtering the input data, using multiple Maps together, and so on.

Syntax

The map operator has the following syntax.

map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R>

project: We use this function to alter the values emitted by the source observable. There are two arguments that the project can accept. The first is value, which is the value that the observable emits. The index number is the second argument. For the initial value emitted, the index number starts at 0 and increases by one for each consecutive value released. It's comparable to an array's index.

thisArg: is optional, and the default value is unknown. It specifies what this is in the context of the project function.

Using Observable Map

We must first import the map from the rxjs/operators library before we can use it.

Then, as demonstrated below, make an observable out of an array of numbers.

srcArray = from([1, 2, 3, 4]);

Invoke the map method using the pipe method.

multiplyBy2() {
  this.srcArray
  .pipe(map(val => { return val * 2}))
  .subscribe(val => { console.log(val)})
}

The project function takes only one input, Val, and multiplies it by two.

map(val => { return val * 2})

Finally, we subscribe to the outcome and print it in the console. 2,4,6,8 is the result.

The diagram below shows how values from the source observable (i.e. 1,2,3,4) pass through the map, which multiplies them by 2 to create new values.

The second argument index can likewise be accessed as illustrated below. For the initial value, it is set to 0 and then incremented for each consecutive value.

multiplyBy2() {

  this.srcArray
    .pipe(map((val, i) => {         //index
      console.log(i)                //0
      return val * 2;
    }))
    .subscribe(val => { console.log(val) })
}

Map Examples

Convert input to upper case

srcName$ = from(['John', 'Tom', 'Katy'])
 
toUpperCase() {
  this.srcName$
   .pipe(map(data => {
     return data.toUpperCase();
   }))
   .subscribe(data => console.log(data))
}

Map to a Single Property

srcObject = from([
  { fName: 'Sachin', lName: "Tendulkar" },
  { fName: 'Rahul', lName: "Dravid" },
  { fName: 'Saurav', lName: "Ganguly" },
]);
 
 
MapToSingleProperty() {
  this.srcObject
   .pipe(map(data => { return data.fName + ' ' + data.lName }))
   .subscribe(data => { console.log(data) })
}
 
//output
Sachin Tendulkar
Rahul Dravid
Saurav Ganguly

Using Map with HTTP Request

The following code obtains a list of dog breeds from the https://dog.ceo/api/breeds/list/all API and transforms the object into an array of key-value pairs using the keyValue pipe.

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { Observable, from, pipe, fromEvent } from 'rxjs';
import { map, filter, tap } from 'rxjs/operators'
import { HttpClient } from '@angular/common/http';
import { KeyValuePipe } from '@angular/common';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [KeyValuePipe]
})
export class AppComponent implements OnInit {
 
constructor(private http: HttpClient,
             private keyValue: KeyValuePipe) {
 }
 
@ViewChild('btn', { static: true }) button: ElementRef;
 
  $dogsBreed(): Observable<any> {
    return this.http.get<any>("https://dog.ceo/api/breeds/list/all")
  }
 
  getDogsBreed() {
 
    this.$dogsBreed()
      .pipe(map(data => {
        var dogs = this.keyValue.transform(data.message)
        console.log(dogs)
      }))
      .subscribe();
 
  }
}

Using with event

You can build an observable from an event and then alter the values using the map.

buttonClick() {
  fromEvent(this.button.nativeElement, 'click')
      .pipe(map( ev => (ev as any).clientX))
      .subscribe(res => console.log(res));
}

map with filter

srcArray = from([1, 2, 3, 4]);
 
  filterWithMap() {
    this.srcArray
    .pipe(
      filter(val => {
        return val > 2;
      }),
      map((val, i) => {
        return val * 2;
      }))
    .subscribe(val => { console.log(val) })
  }

Multiple maps

Multiple map functions are used in the following instances. The first map multiplies by ten, while the second adds two.

mulitpleMaps() {
  this.srcArray
  .pipe(
    map(val => {
      return val + 10;
    }),
    map((val, i) => {
      return val * 2;
    }))
  .subscribe(val => { console.log(val) })
}

Conclusion

In this article, we learned how to use the Map operator with examples such as changing the source to upper case, using Map with the Angular HTTP Request, with DOM events, filtering the input data, using multiple Maps together, and so on.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in the comment section.

Post a Comment

Previous Post Next Post