Search code examples
javascriptangularobservableangular-pipengx-charts

Ngx-charts can't load bar charts directly with async pipe in angular


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.

Barchart

Barchart code

Error

Empty chart


Solution

  • Cause

    This is happening because the component 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 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 when results is set to null 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 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 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 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 component.