Back to course

Common Operators: tap, delay, and catchError

The Complete Angular Developer: From Zero to Hero

55. Common Operators: tap, delay, and catchError

These operators are critical for debugging, controlling timing, and handling stream failures.

1. tap (Side Effects)

tap allows you to execute side effects (like logging, setting component state, debugging) without altering the values passing through the Observable stream.

typescript import { tap } from 'rxjs/operators';

this.dataService.getUsers().pipe( tap(data => { // This is useful for debugging: look at the data before processing console.log('DEBUG: Data received from API:', data); this.isLoading = false; // Set component state here (a side effect) }), map(users => users.length) // The pipe continues as usual ).subscribe(count => console.log('Total users:', count));

2. delay (Timing Control)

delay pauses the stream for a specified time before re-emitting the value. Useful for simulating network latency or visual transitions.

typescript import { delay } from 'rxjs/operators';

of('A', 'B', 'C').pipe( delay(2000) // Wait 2 seconds before emitting the sequence ).subscribe(val => console.log(val));

3. catchError (Error Handling)

As discussed in the HTTP section, catchError intercepts errors from the source Observable. It allows you to handle the error, log it, and then either rethrow the error or provide a new Observable stream to keep the application running (a fallback stream).

typescript import { catchError, of } from 'rxjs/operators'; import { throwError } from 'rxjs';

// ... imagine an observable that might fail

failedObservable$.pipe( catchError(err => { console.error('Operation failed, using fallback data.', err); // Option 1: Provide a fallback value/stream (the stream continues) return of([]);

// Option 2: Rethrow a new error (the stream terminates)
// return throwError(() => new Error('Critical failure'));

}) ).subscribe(data => { // data will be the original data OR the empty array fallback });