Learn RxJS
Search…
tap / do

signature: tap(nextOrObserver: function, error: function, complete: function): Observable

Transparently perform actions or side-effects, such as logging.

πŸ’‘ If you are using as a pipeable operator, do is known as tap!
​​
​
​

Examples

Example 1: Logging with tap
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { tap, map } from 'rxjs/operators';
4
​
5
const source = of(1, 2, 3, 4, 5);
6
// transparently log values from source with 'tap'
7
const example = source.pipe(
8
tap(val => console.log(`BEFORE MAP: ${val}`)),
9
map(val => val + 10),
10
tap(val => console.log(`AFTER MAP: ${val}`))
11
);
12
​
13
//'tap' does not transform values
14
//output: 11...12...13...14...15
15
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Using tap with object
1
// RxJS v6+
2
import { of } from 'rxjs';
3
import { tap, map } from 'rxjs/operators';
4
​
5
const source = of(1, 2, 3, 4, 5);
6
​
7
// tap also accepts an object map to log next, error, and complete
8
const example = source
9
.pipe(
10
map(val => val + 10),
11
tap({
12
next: val => {
13
// on next 11, etc.
14
console.log('on next', val);
15
},
16
error: error => {
17
console.log('on error', error.message);
18
},
19
complete: () => console.log('on complete')
20
})
21
)
22
// output: 11, 12, 13, 14, 15
23
.subscribe(val => console.log(val));
Copied!

Additional Resources

Last modified 9mo ago