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
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();

Leave a Reply

Your email address will not be published. Required fields are marked *