getData() {
return this.http.get('/api/data').pipe(
tap(data => console.log('Data received:', data))
);
}What is the main purpose of the
tap operator here?getData() {
return this.http.get('/api/data').pipe(
tap(data => console.log('Data received:', data))
);
}The tap operator is used to perform side effects like logging without modifying the data stream. It passes the original data unchanged to the next operator or subscriber.
of(1, 2, 3).pipe(
tap(x => console.log('Side effect:', x)),
map(x => x * 10)
).subscribe(result => console.log('Result:', result));What will be the console output sequence?
of(1, 2, 3).pipe( tap(x => console.log('Side effect:', x)), map(x => x * 10) ).subscribe(result => console.log('Result:', result));
The tap logs the original values 1, 2, 3. Then map multiplies each by 10 before emitting. So logs show side effects with original values, results with multiplied values.
loading = true before an HTTP call and loading = false after it completes using tap. Which code snippet is correct?loading = false; fetchData() { this.loading = true; this.http.get('/api/items').pipe( tap({ next: () => this.loading = false, error: () => this.loading = false }) ).subscribe(); }
Option A uses the object form of tap to handle both next and error callbacks, ensuring loading is set to false in both cases.
this.http.get('/api/data').pipe(
tap(data => { this.processData(data); })
).subscribe();Inside
processData, this is undefined. Why?this.http.get('/api/data').pipe( tap(data => { this.processData(data); }) ).subscribe();
The callback function passed to tap is a normal arrow function, but if the surrounding context is lost or the code is extracted, this may not refer to the component instance. Binding or using arrow functions carefully is needed.
tap and map operators in RxJS.tap is used for side effects like logging and does not modify the data stream. map transforms each emitted value into a new value.