tap() is an operator of rxjs library (used in Angular) which in my personnel view is very helpful when you are working with observables for side effects – which means doing something without affecting the the actual observable stream.
Documentation says:-
Used to perform side-effects for notifications from the source observable
My definition :-
tap() is the tool which lets us look inside or act on the data flowing through an observable — without changing the data.
It is that spy that watches data go by and logs it, stores it, triggers something… but doesn’t alter the flow.
Importing the operator
import { tap } from 'rxjs/operators';
tap() operator Syntax
myObservable$
.pipe(
tap(value => {
// Do something with value
})
)
.subscribe();
Example
I used the tap() operator to update/patch my reactive form without changing the data stream. But we are following:-
- repo files – where we have http methods like get, post, put, patch, delete, download etc.
- service files – where we have calling to the http methods in the repo files.
- component – from where we are calling our services to fetch data.
//repo
get(): Observable<> {
return this.http.get<User>('/api/user/1');
}
// service
getUser(): Observable<User> {
return this.repo.get();
}
// component
this.userService.getUser()
.pipe(
tap(user => this.userForm.patchValue(user))
)
.subscribe();
Advance Use Case
this.http.get('/api/data')
.pipe(
tap({
next: data => console.log('Data:', data),
error: err => console.error('Error:', err),
complete: () => console.log('Stream complete!')
})
).subscribe();