My problem is similar to this stackoverflow post
When I use async pipe to observe data from firebase and show it in chart, I can see the chart but prompt null error in console. Without async pipe, all errors are gone but I can't fetch data (duh it's async data). Help me please.
Cause
This is happening because the component cannot work with
null
values forresults
.Why?
Async pipe is, as you say, used when you do not want to (or do not need to) subscribe in the component code, but do it in the template instead. Pipe, however, is a pure function: is has to return something each time it's called.
When th async pipe is called before data has arrived from the server, the pipe returns
null
, having no better value to offer.Based on the screeshot of the error trace, it looks like
ngx-charts-bar-vertical
does not work whenresults
is set tonull
and it breaks then.A fix
You need to not render the bar chart component at all while data is not present. You can do this by utilizing the
NgIf
directive, which allows you to do a binding in the template withas
. Super-useful for exactly these cases where you want to conditionally show a part of the template, but then re-use this value again.While
surveryAnswers
observable doesnt emit anything, the component will not be rendred, thus there will be no error. When it emits,async
pipe will catch that, trigger CD and it won't benull
anymore -- it will be a truthy value, which then gets fed into a variable calledanswers
that we use to feed into theresults
input of the component.