无法使用highcharts在angularjs中绘制饼图

时间:2018-12-19 22:30:02

标签: javascript angularjs highcharts

我有一个AngularJS应用程序(angularJS 1),我正在尝试使用从API中获取的数据创建基本的饼图,这是我的代码:

index.html:

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>My Page</title>
  <meta name="viewport" content="width=device-width">
  <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
  <link rel="stylesheet" href="styles/main.css">
</head>
<body ng-app="myApp">
  <div ng-controller="myCtrl" class="wrapper">
    This is my Pie Chart:
    <br>
    <div id="mypie"></div>
  </div>
  <script src="bower_components/angular/angular.js"></script>
  <script src="bower_components/jquery/dist/jquery.js"></script>
  <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
  <script src="bower_components/highcharts/highcharts.js"></script>

  <script src="scripts/app.js"></script>
</body>
</html>

app.js

angular.module('myApp').controller('myCtrl', ['$scope', '$http', function ($scope, $http) {
  $scope.fetchData = function () {
  var url = 'http://localhost:8080/service/piedata';
  $http({
      method: 'GET',
      url: url
    })
    .then(
      function (response) {
        $scope.myData = response.data;
        console.log($scope.myData);
        var chartConfig = {
          chart: {
            type: 'pie'
          },
          title: {
            text: 'My Pie Chart'
          },
          tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
          },
          plotOptions: {
            pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                  color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
              }
            }
          },
          series: [{
            data: $scope.myData
          }]
        };
        Highcharts.chart('mypie', chartConfig);
      },
      function (err) {
        console.log('ERROR: ' + JSON.stringify(err));
      }
    );
  };

  $scope.fetchData();
}]);

我回复的数据是这样的:

[{ '3': 10 }, { '4': 60 }, { '5': 30 }];

现在,当我运行应用程序时,我可以看到页面加载和静态内容以及饼图的白色区域,但是看不到任何数据加载。

我在做什么错了?

编辑:

忘记了在声明角度模块的地方添加main.js文件。

main.js

angular.module('myApp', ['ui.router','ngMaterial','highcharts-ng'])

//there is some other stuff in this file like filters and config which is irrelevant here.

2 个答案:

答案 0 :(得分:1)

几件事...

  • myData的结构必须为[{                        名称:“您的标签名称”,                        y:56.33                    },...]
  • 角度声明应为angular.module('myApp',[]
  • 您可以再次添加$ http ...,但是请确保格式符合highcharts要求

下面的工作示例:

angular.module('myApp', [])
    .controller('myCtrl', ['$scope', function ($scope) {
      $scope.fetchData = function () {
          
            $scope.myData = [{ 'name':'3', y: 10 }, { 'name':'4', y: 60 }, { 'name':'5' ,y: 30 }];
            //console.log($scope.myData);
            var chartConfig = {
              chart: {            type: 'pie'          },
              title: {            text: 'My Pie Chart'          },
              tooltip: {            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'          },
              plotOptions: {
                pie: {              allowPointSelect: true,              cursor: 'pointer',              dataLabels: {                enabled: true,                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                    style: {                  color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'                }
                  }
                }
              },
              series: [{
                data: $scope.myData
              }]
            };
            Highcharts.chart('mypie', chartConfig);
      };

      $scope.fetchData();
    }]);
<div ng-app="myApp">
  <div ng-controller="myCtrl" class="wrapper">
    This is my Pie Chart:
    <br>
    <div id="mypie"></div>
  </div>
</div>



<link href="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.2.0/css/highcharts.css"rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.2.0/highcharts.js"></script>

答案 1 :(得分:1)

您要渲染饼图的数据点与Highchart文档的格式不正确。您可以在https://www.highcharts.com/demo/pie-basic上查看饼图的演示。

series的结构是:

    series: [{
        data: [{
            name: 'Chrome',
            y: 61.41
        }, {
            name: 'Internet Explorer',
            y: 11.84
        }, {
            name: 'Firefox',
            y: 10.85
        }]
    }]

您的API返回响应的格式为[{ '3': 10 }, { '4': 60 }, { '5': 30 }];,因此您可以在服务器上对其进行修复(有意义的更改响应API)或(在客户端上)更改响应的格式:

const dataChart = myData.map(d => {
   const name = Object.keys(d)[0];
   return { name, y: d[name] }
})

series: [{
  data: dataChart
}]

在与angular.module('myApp', [])配合使用之前,还应声明您的角度应用angular.module('myApp').controller('myCtrl', ...。我认为您已经声明了它,所以我认为这不是错误。

我在http://5c1b231ee193d000132a73a8.mockapi.io/api/53860059用简单的API创建了一个演示。这是jsfiddle https://jsfiddle.net/huynhsamha/fd80g7rp/

上的演示

您也可以在以下代码段上运行它:

angular.module('myApp', []).controller('myCtrl', ['$scope', '$http', function ($scope, $http) {

  const fetchData = function () {
    const url = 'https://5c1b231ee193d000132a73a8.mockapi.io/api/53860059';
    $http({ method: 'GET', url })
      .then(function (response) {
        const myData = response.data;
        console.log(myData);
        
        const dataChart = myData.map(d => {
          const name = Object.keys(d)[0];
          return { name, y: d[name] }
        })
        
        console.log(dataChart);
          
        const chartConfig = {
          chart: {
            type: 'pie'
          },
          title: {
            text: 'My Pie Chart'
          },
          tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
          },
          plotOptions: {
            pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                  color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
              }
            }
          },
          series: [{
            data: dataChart
          }]
        };

        Highcharts.chart('mypie', chartConfig);
      
      }, function (err) {
        console.log(err);
      });
  };

  fetchData();
}]);
<html ng-app="myApp">
<body>

<div ng-controller="myCtrl" class="wrapper">
  This is my Pie Chart:
  <br>
  <div id="mypie"></div>
</div>

</body>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>

<script src="https://code.highcharts.com/highcharts.src.js"></script>

</html>