Debugging page
Learn how to debug RxJS with the tap operator.
Video
Who has time to read? This video covers the content on this page. Watch fullscreen.
The problem
In this section, we will:
- Learn how to debug RxJS observables.
- Log the value of the
this.cardNumber$
observable everytime it changes.
How to solve this problem
- Create a
log
helper thatconsole.log
s emitted values without causing side-effects. - Use the
log
helper to log values emitted bythis.cardNumber$
.
What you need to know
RxJS can be tricky to debug. It seems like you should simply be able to subscribe to an observable and output its values.
The problem with this is that:
- Subscribing to an observable changes the state of the observable.
- Observables (in contrast to Subjects) run their initialization code every time there is a new subscriber.
Many times you want to subscribe to an intermediate observable to see its value.
The following example creates:
randomNumbers
to emit random numbers.floats0to100
to emit the random numbers multiplied by 100.ints0to100
to emit the multiplied numbers rounded to the nearest integer.
If you subscribe
to floats0to100
to see its values, you will notice
that the float
values do not match the int
values!!
The tap operator allows you to perform a side-effect (such as logging) on every emission on a source observable.
The following uses tap to log floats0to100
values so they match:
We can generalize this pattern with a log
operator like:
log
can be used as follows:
NOTE 1: Notice that to log
number
, we call.pipe(log(...))
on what would be thenumber
observable.
NOTE 2: The solution will log
cardNumber
twice. That’s expected because there are two subscriptions oncardNumber
:
- one directly from
cardNumber$
in the template -{{ cardNumber$ | async }}
- the other from
cardError$
in the template -{{ cardError$ | async }}
-cardError
derives fromcardNumber
.