Firebase数据未在HighCharts中绘图

时间:2018-05-17 11:43:09

标签: javascript firebase firebase-realtime-database highcharts

我想使用Highcharts使用我的Firebase数据绘制图表。图表的轴出现了,但我没有绘制图表。

This is the data printed on my HTML console.

我正在使用的Javascript代码:

var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
};

firebase.initializeApp(config);
var dbRef0 = firebase.database().ref().child("");
var dbRef1 = firebase.database().ref().child("Meter2");
var dataSetFirebaseTotalActivePower1 = [];

dbRef1.limitToLast(20).on('child_added',function(snap) {
    var TotalActivePower1 = snap.val().totalActivePower;
    var Time1 = snap.val().time;
    dataSetFirebaseTotalActivePower1.push({x: Time1 ,y: TotalActivePower1});
    console.log(dataSetFirebaseTotalActivePower1);
});

Highcharts.chart('container', {
    chart: {
        type: 'areaspline'
    },
    title: {
        text: 'Total Active Power Graph'
    },
    legend: {
        layout: 'vertical',
        align: 'left',
        verticalAlign: 'top',
        x: 150,
        y: 100,
        floating: true,
        borderWidth: 1,
        backgroundColor: (Highcharts.theme && 
            Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
    },
    xAxis: {
        type: 'datetime',
        title: {
            text: 'Time'
        },
        plotBands: [{ 
            from: 4.5,
            to: 6.5,
            color: 'rgba(68, 170, 213, .2)'
        }]
    },
    yAxis: {
        title: {
            text: 'Total Active Power, kWh'
        }
    },
    tooltip: {
        shared: true,
        valueSuffix: ' units'
    },
    credits: {
        enabled: false
    },
    plotOptions: {
        areaspline: {
            fillOpacity: 0.5
        }
    },
    series: [{
        data: [dataSetFirebaseTotalActivePower1]
    }]
});

图表出现,但为空。

1 个答案:

答案 0 :(得分:0)

您的图表配置对我来说很好,您遇到的是来自firebase的数据是异步进入的,这意味着在创建图表时,您的数组是空的,只有这样节点才会启动一个接一个地倒进去。

您可以通过addPoint API调用将数据直接添加到图表中,而不是填充结果数组:

  

渲染时间后向系列添加一个点。可以在结尾处添加该点,或者在该系列的开头或中间添加一个X值。

对您的child_added事件回调尝试此更新:

dbRef1.limitToLast(20).on('child_added', function(snap) {
    var TotalActivePower1 = snap.val().totalActivePower;
    var Time1 = snap.val().time;
    var DataPoint = { x: Time1, y: TotalActivePower1 };
    chart.series[0].addPoint(DataPoint, true);
});

了解Why are the Firebase API asynchronous?

可能对您有所帮助