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.
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.
Share Improve this question asked Dec 15, 2017 at 6:01 phonemyattphonemyatt 1,3772 gold badges17 silver badges36 bronze badges1 Answer
Reset to default 7Cause
This is happening because the ponent cannot work with null
values for results
.
Why?
Async pipe is, as you say, used when you do not want to (or do not need to) subscribe in the ponent 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 when results
is set to null
and it breaks then.
A fix
You need to not render the bar chart ponent 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 with as
. Super-useful for exactly these cases where you want to conditionally show a part of the template, but then re-use this value again.
<ngx-charts-bar-vertical *ngIf="surveyAnswers | async as answers"
[results]="answers"
></ngx-charts-bar-vertical>
While surveryAnswers
observable doesnt emit anything, the ponent will not be rendred, thus there will be no error. When it emits, async
pipe will catch that, trigger CD and it won't be null
anymore -- it will be a truthy value, which then gets fed into a variable called answers
that we use to feed into the results
input of the ponent.