What does tap() do?
tap() in RxJS is an operator that lets you run side effects without changing the stream itself.
A simple example:
ts
import { of } from 'rxjs';
import { tap, map } from 'rxjs/operators';
of(1, 2, 3)
.pipe(
tap(val => console.log('Received:', val)),
map(val => val * 10)
)
.subscribe(result => console.log('Result:', result));Outputs:
javascript
Received: 1
Result: 10
Received: 2
Result: 20
Received: 3
Result: 30Why you need tap():
- For logging and debugging
- For calling methods (for example, showing/hiding a loading indicator)
- For saving to localStorage, sending analytics, and so on
- It doesn't change the stream's values, it just observes
Where it's used:
ts
this.http.get('/api/data')
.pipe(
tap(() => this.isLoading = true),
tap(data => console.log('Data arrived:', data)),
tap(() => this.isLoading = false)
)
.subscribe();Conclusion:
tap() is like a mirror beside the stream:
you see what's happening, you can do something,
but you don't touch the data itself.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.