Angular tap vs map




Asked on November 19, 2018
What is the difference between tap and map in Angular? 



Replied on November 19, 2018
tap and map both are RxJS operator.

1. tap


RxJS tap performs side effects for every value emitted by source Observable and returns an Observable identical to the source Observable until there is no error. tap is the pipeable operator and it is the changed name of the RxJS do operator. Angular 6 uses RxJS 6 that has been shipped with pipeable operators which can be used independent of an Observable. To avoid the conflict with JavaScript keyword, some RxJS operators name has been changed such as do changed to tapcatch changed to catchErrorswitch changed to switchAll and finally changed to finalize. These operators are imported from rxjs/operators. For example tap is imported as following.
import { tap } from 'rxjs/operators'; 
Pipeable operators such as tap, are used within pipe function of Observabletap performs side effects only when the Observable returned by tap is subscribed. tap can be used to debug values emitted by Observable or to perform any side effect.

 tap is declared as following.
public tap(nextOrObserver: Observer | function, error: function, complete: function): Observable 
tap has three optional parameters. 
nextOrObserver: A normal Observable object to perform side effect. 
error: Callback for errors in source Observable
complete: Callback for completion of the source. 

Find the sample example.
of(1, 2, 3, 4).pipe(
 tap(el => console.log("Process "+ el),
	err => console.error(err),
	() => console.log("Complete")
 ),
 filter(n => n % 2 === 0)
).subscribe(el => console.log("Even number: "+ el)); 
We will get following output.
Process 1
Process 2
Even number: 2
Process 3
Process 4
Even number: 4
Complete 


2. map


map is a RxJS pipeable operator. map applies a given function to each element emitted by the source Observableand emits the resulting values as an Observablemap is imported as following.
import { map } from 'rxjs/operators'; 
map is used with pipe which is an instance method of Observable
Suppose we have an Observable of a string that contains comma separated names.
getStdNames(): Observable<string> {
   return of("Mahesh, Krishna, Ram");
} 
Now we will map this string into array and return result into Observable of array of names.
stdNames$: Observable<string[]>; 
getStdNames() { 
 this.stdNames$ = this.bookService.getStdNames().pipe(
    map(res => res.split(","))
 ); 
}
We can iterate stdNames$ as following.
<ul>
  <li *ngFor="let name of stdNames$ | async" >
    {{name}}
  </li>
</ul> 
It will print 

Mahesh
Krishna
Ram





Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us