最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 7

Cause

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.

发布评论

评论列表(0)

  1. 暂无评论