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

ε祈祈猫儿з 提交于 2019-12-07 17:37:25

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!