Angular tap vs do




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


Replied on November 19, 2018
tap  and do  are same RxJS operators.

tap is changed name of do in RxJS 5.5+ . Angular 6 integrates RxJS 6. RxJS tap and do  are same operator. In Angular 6+, we need to use tap operator. tap/do 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/do performs side effects only when the Observable returned by them are subscribed. tap can be used to debug values emitted by Observable or to perform any side effect.

1. tap

 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 Observable

Find the sample example.

of(1, 2, 3, 4).pipe(
  tap(el => console.log("Process "+ el)),
  filter(n => n % 2 === 0)
).subscribe(el => console.log("Even number: "+ el)); 

References


2. do

Till Angular 5, we use RxJS do operator. It is imported as following.
import 'rxjs/add/operator/do';
Find the sample example.

of(1, 2, 3, 4)
.do(el => console.log("Process "+ el))
.filter(n => n % 2 === 0)
.subscribe(el => console.log("Even number: "+ el)); 

Reference




Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us