Observing with tap
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 22 of 24.
Sometimes you want to log a response without changing it. RxJS tap runs a function when a value passes through the stream. Pipe attaches operators such as tap to an observable.
return of({ready: true}).pipe(
tap(value => console.log(value.ready))
);The log is a side effect: the emitted value stays the same. Return the result of pipe so Nest consumes that stream. Calling pipe and then returning a different observable leaves this work unused. Nest validation pipes are a separate feature despite sharing the word pipe. Here this method belongs to the RxJS observable.
The callback receives the emitted value. If the source emits later, logging outside tap runs too soon and cannot read that value. A type such as Observable<number> describes the values carried by the stream.
Challenge
EasyContinue alongside your task tracker. Edit practice-tap/exercise.ts. The supplied source emits an object with a numeric id after a short delay. Return that source piped through tap. When its value arrives, print Sending followed by the emitted id. Leave the value unchanged.
Try it: GET /result returns {"id":1}; the Console ends with Waiting for subscription, Source subscribed, then Sending 1. GET /result?id=7 returns {"id":7} and logs Sending 7 after subscription.
Try it yourself
import { Observable, tap } from 'rxjs';
export function exercise(source: Observable<{ id: number }>) {
return source;
}
All lessons in TypeScript and NestJS
1Nest Basics
Classes and MethodsHello, NestRegistering a Controller4Guards, Filters, Interceptors
GuardsPractice on your own: Express playground