无法读取属性'未定义的:当试图通过$http.get获取数据

Cannot read property 'datasets' of undefined: when trying to fetch data through $http.get

本文关键字:http 数据 获取 get 属性 读取 未定义      更新时间:2023-09-26

我有一个使用chart.js的应用程序。

指令如下:

.directive('chart', function () {
        var baseWidth = 600;
        var baseHeight = 400;
        return {
            restrict: 'E',
            template: '<canvas></canvas>',
            scope: {
                chartObject: "=value",
                data: "="
            },
            link: function (scope, element, attrs) {
                var canvas  = element.find('canvas')[0],
                    context = canvas.getContext('2d'),
                    chart;
                var options = {
                    type:   attrs.type   || "Line",
                    width:  attrs.width  || baseWidth,
                    height: attrs.height || baseHeight
                };
                canvas.width = options.width;
                canvas.height = options.height;
                chart = new Chart(context);
                var chartType = attrs.type;
                chart[chartType](scope.data, options);
                //Update when charts data changes
                scope.$watch(function() { return scope.chartObject; }, function(value) {
                    if(!value) return;
                    var chartType = options.type;
                    chart[chartType](scope.chartObject.data, scope.chartObject.options);
                });
            }
        };
    })

然后是包含chart元素的部分:

<div class="page page-charts">
    <section data-ng-controller="chartjsCtrl2">
        <div class="row">

            <div class="col-md-6">
              <section class="md-content-section">
                <md-toolbar class="md-accent">
                  <div class="md-toolbar-tools">
                    Bar Chart js
                  </div>
                </md-toolbar>
                <md-content>
                  <div class="md-content__body">
                    <chart class="chartjs" data-data="chartjsBar" data-type="Bar" value="myChart"></chart>
                  </div>
                </md-content>
              </section>
            </div>
        </div>
    </section>
</div>
最后,有趣的部分,控制器:
.controller("chartjsCtrl2", ["$scope","config","myService","$http",
    function ($scope,config,myService,$http) {
        var inputData=$scope.inputData;
        var promise=$http.get('http://localhost:8080/getChartData');
        //console.log(dataInput);
        promise.success(function(data){
            return $scope.chartjsBar = {
            labels: ["January", "February", "March", "April", "May", "June", "July"],
            datasets: [
                {
                    label: "My First dataset",
                    fillColor: config.primary_color,
                    strokeColor: config.primary_color,
                    highlightFill: config.primary_color,
                    highlightStroke: config.primary_color,
                    data:data
                },
                {
                    label: "My Second dataset",
                    fillColor: config.color_warning,
                    strokeColor: config.color_warning,
                    highlightFill: config.color_warning,
                    highlightStroke: config.color_warning,
                    data:data
                }
            ]
        }           
        })
        promise.success(function(data){
            console.log(data);
            dataInput=data;
        });
 }
])

现在的问题是它没有显示条形图。我根本无法得到这个运行,即使我把硬编码的值在数据集的数据字段。有人能帮忙吗?

编辑:-我必须澄清。如果不在http的成功回调函数中,代码就可以工作。

参见https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js

var useLegacyPromise = true; /** * @ngdoc method * @name $httpProvider#useLegacyPromiseExtensions * @description * * Configure $http service to return promises without the shorthand methods success and error . * This should be used to make sure that applications work without these methods. * * Defaults to true. If no value is specified, returns the current configured value. * * @param {boolean=} value If true, $http will return a promise with the deprecated legacy success and error methods. * * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. * otherwise, returns the current configured value. **/ this.useLegacyPromiseExtensions = function(value) { if (isDefined(value)) { useLegacyPromise = !!value; return this; } return useLegacyPromise; };

promise()方法已弃用,所以只使用then()方法,

promise()方法自己使用'then()'方法:

if (useLegacyPromise) {
    promise.success = function(fn) {
      assertArgFn(fn, 'fn');
      promise.then(function(response) {
        fn(response.data, response.status, response.headers, config);
      });
      return promise;
    };
    ....

,但注意promise()得到响应。数据then()得到响应。在你的情况下,我会尽量坚持使用then()方法:

var promise=$http.get('http://localhost:8080/getChartData').then(function (response) {
  // your data is under response.data now
  .......
}, optionalErrorFunc, optionalNotifyFunc);