当Firebase数据发生变化时,Google 图表不会更新

Google Charts doesn't get updated when Firebase data has changed

本文关键字:Google 更新 数据 Firebase 变化      更新时间:2023-09-26

我已经设法将我的 Firebase 连接到 Google 图表,效果很好,但我正在努力如何显示一条简单的消息说"没有数据"如果没有数据计算为我声明的简单 if else 表达式。

例如,我为单个用户设置了 Firebase 数据值"NA",这在理论上意味着图表默认情况下不会显示,并且错误消息会在页面加载时显示,并且在任何时候都会更改回此值。但是,情况并非如此,触发它的唯一方法是单击我在 HTML 文件中设置的 3D 按钮。此外,当 Firebase 数据更改为大于零的值时,错误消息仍会显示。

这是我的代码:

JS文件

var displayMode = true;
$scope.statistics = function () {
    $mdSidenav('left').close();
    $state.go('statistics');
    $timeout(function () {
        setUpChart();
        var timer;
        $(window).on('resize', function () {
            clearTimeout(timer);
            timer = setTimeout(function () {
                setUpChart();
            }, 250);
        });
    });
};
function setUpChart() {
    $.ajax({
        url: '//www.google.com/jsapi',
        dataType: 'script',
        cache: true,
        success: function () {
            google.load('visualization', '1', {
                'packages': ['corechart'],
                'callback': drawChart
            });
        }
    });
    function drawChart() {
        // This links to my Firebase url
        userRef.on('value', function (snapshot) {
            var pass = 0;
            var fail = 0;
            snapshot.forEach(function (snapshot) {
                var userResults = snapshot.val();
                if (userResults.passFail === 'Pass') {
                    pass = pass + 1;
                }
                if (userResults.passFail === 'Fail') {
                    fail = fail + 1;
                }
            });
            if (pass === 0 && fail === 0) {
                console.log('No data: ' + pass + ' & ' + fail);
                $scope.error = true;
                $scope.errorMessage = 'No user data available, please try  
                again later.';
            } else {
                console.log('Is data: ' + pass + ' & ' + fail);
                $scope.error = false;
                $scope.errorMessage = null;
                var data = new google.visualization.DataTable();
                data.addColumn('string', 'Result');
                data.addColumn('number', 'Delegates');
                data.addRows([
                    ['Pass', pass],
                    ['Fail', fail]
                ]);
                var options = {
                    'is3D': displayMode,
                    'chartArea': {'width': '100%', 'height': '80%'},
                    'legend': {'position': 'top', 'alignment': 'center'}
                };
                var chart = new 
         google.visualization.PieChart(document.getElementById('pieChart'));
                chart.draw(data, options);
            }
        });
    }
}
// Changes chart type to 3D or top view on a butto click
$scope.chartFormat = function () {
    if (displayMode == true)
        displayMode = false;
    else
        displayMode = true;
    setUpChart();
};

.HTML

<div class="container" style="padding-top: 100px; padding-bottom: 50px">
<button data-ng-model="displayType" style="display: block; margin: 0 auto"
        data-ng-click="displayType=displayType ? false : true;  
        chartFormat()"
        class="btn btn-default btn-md" type="button"><i class="material-
        icons">3d_rotation</i></button>
<div data-ng-if="error" class="alert alert-danger">
   <span data-ng-if="errorMessage" class="glyphicon glyphicon-remove">  
   </span><strong> {{errorMessage}}</strong>
</div>
<div id="pieChart" style="display: block; margin: 0 
auto; width: 100%; height: 500px"></div>
</div>

如果有人遇到与我上面类似的问题,只需将 data-ng-init="function_name_here()" 添加到您希望在 html 中显示的错误消息div 中,如果您的 Google 图表没有数据。

以前从未想过这一点,但现在可以享受并在我的情况下动态显示错误消息,如果数据存在,则删除该消息!

只要

Firebase 中的数据发生变化,您在 userRef.on('value', function (snapshot) { 中的代码就会异步运行。此时AngularJS并不期望$scope发生变化,所以它看不到它们。

解决方案是让 AngularJS 意识到您更改了$scope的事实,方法是按照 charlieftl 建议调用$scope.$apply()或将其包装在$timeout()中,以便在下一个摘要周期中拾取它:

userRef.on('value', function (snapshot) {
    $timeout(function() {
        var pass = 0;
        var fail = 0;
        snapshot.forEach(function (snapshot) {
            var userResults = snapshot.val();
            if (userResults.passFail === 'Pass') {
                pass = pass + 1;
            }
            if (userResults.passFail === 'Fail') {
                fail = fail + 1;
            }
        });
        if (pass === 0 && fail === 0) {
            console.log('No data: ' + pass + ' & ' + fail);
            $scope.error = true;
            $scope.errorMessage = 'No user data available, please try  
            again later.';
        } else {
            console.log('Is data: ' + pass + ' & ' + fail);
            $scope.error = false;
            $scope.errorMessage = null;
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Result');
            data.addColumn('number', 'Delegates');
            data.addRows([
                ['Pass', pass],
                ['Fail', fail]
            ]);
            var options = {
                'is3D': displayMode,
                'chartArea': {'width': '100%', 'height': '80%'},
                'legend': {'position': 'top', 'alignment': 'center'}
            };
            var chart = new 
     google.visualization.PieChart(document.getElementById('pieChart'));
            chart.draw(data, options);
        }
    });
});