0
0
Angularframework~5 mins

tap operator for side effects in Angular

Choose your learning style9 modes available
Introduction

The tap operator lets you run extra code when data flows through an observable without changing the data itself.

Logging values passing through an observable to see what data is flowing.
Triggering a loading spinner when a request starts and stops.
Performing side actions like updating a variable or calling a function without affecting the main data.
Debugging observable streams by inspecting values without modifying them.
Syntax
Angular
observable$.pipe(
  tap(value => {
    // side effect code here
  })
)

The tap operator does not change the data passing through.

It is used inside the pipe method of an observable.

Examples
Logs each value passing through without changing it.
Angular
import { tap } from 'rxjs/operators';

myObservable.pipe(
  tap(value => console.log('Value:', value))
).subscribe();
Runs different side effects for next, error, and complete events.
Angular
myObservable.pipe(
  tap({
    next: value => console.log('Next:', value),
    error: err => console.error('Error:', err),
    complete: () => console.log('Done')
  })
).subscribe();
Sample Program

This Angular component creates an observable of numbers 1, 2, and 3. The tap operator logs each value as a side effect. The subscribe then logs the received values.

Angular
import { Component } from '@angular/core';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';

@Component({
  selector: 'app-tap-example',
  template: `<p>Check the console for tap operator output.</p>`
})
export class TapExampleComponent {
  constructor() {
    of(1, 2, 3).pipe(
      tap(value => console.log('Side effect:', value))
    ).subscribe(value => console.log('Received:', value));
  }
}
OutputSuccess
Important Notes

Use tap only for side effects, not to change data.

Side effects run every time the observable emits a value.

Summary

tap lets you peek at data without changing it.

It is great for logging, debugging, or triggering side actions.

Always use it inside pipe with observables.