【发布时间】:2018-10-16 07:34:14
【问题描述】:
我的 Firebase 数据库中有一个结构为 的基本数据。在我的 Angular 应用程序中,我想使用这些数据绘制图表。 这是我的代码:
import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Chart } from 'chart.js';
import {AngularFireDatabase} from 'angularfire2/database'
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
chart = [];
arraytoPassChart = []
@ViewChild('lineCanvas') lineCanvas;
constructor(public navCtrl: NavController, private db: AngularFireDatabase) { }
ionViewDidLoad() {
this.db.list('/percentage')
.valueChanges()
.map(res => {
// do some calculations here if you want to
return res.map(eachlLabel => eachlLabel)
})
.subscribe(res => {
console.log(res)//should give you the array of percentage.
this.arraytoPassChart.push(res);
})
this.chart = new Chart(this.lineCanvas.nativeElement, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: this.arraytoPassChart,// my data here, work when I type an array myself
spanGaps: false,
}
]
}
});
}}
在this question,有人向我解释了从 firebase 检索数据的正确方法。在我的代码中,当我将结果记录到控制台时,我将数据作为一个数组,我想用 Chartjs 绘制图表。
console.log(res)//should give you the array of percentage.
但是当页面加载时它不显示数据。 但是当我自己输入数据而不是传递数组时它可以工作。
我真的很好奇我错过了什么,我怀疑 Chartjs 试图在它拥有数据之前绘制图表,但我也想不出解决这个问题的方法。如果有解决方案,我会很高兴。
【问题讨论】:
标签: angular firebase ionic-framework firebase-realtime-database chart.js