Angular UI-Grid TypeError: Cannot set property 'data' of undefined. Sending a promise from Service and data coming as undefined

Angular UI-Grid TypeError: Cannot set property 'data' of undefined. Sending a promise from Service and data coming as undefined

我正在探索 Angular.js UI-Grid。但是,当我在我的服务中发出 HTTP 请求时,我似乎无法弄清楚为什么数据未定义。当我从我的控制器发出 HTTP 请求时,它似乎工作正常。如何使 Ui-Grid 以模块化方式工作?

HTML

<div id="grid1" ui-grid="gridOptions" class="grid"></div>

控制器

app.controller('tableCtrl', function($scope, tableService) {

    var getAllArtistData = function() {

        tableService.getArtistData().then(function(data) {
            console.log("this is controller data", data);
            $scope.gridOptions.data = data;

            $scope.gridOptions = {};

            $scope.gridOptions.columnDefs = [
                {name:'artist_id'},
                {name:'first_name'}
            ];

            });
        };
    getAllArtistData();
});

服务

app.service('tableService', function($http, $q) {

    /************************************************
    GET ARTIST DATA 
    ************************************************/
    this.getArtistData = function() {

        var defer = $q.defer();

        $http.get('../../../data/artists-lite.json')
            .success(function(response) {
                console.log("this is response", response);
                defer.resolve(response);
            })
            .error(function(err) {
                defer.reject(err);
            });

        return defer.promise;

    };
});

App.js

'use strict';

var app = angular.module('bucketfeet', ['ui.router','ui.grid', 'ngAnimate']);

app.run(function($state, $rootScope) {
    $rootScope.$state = $state;
});

app.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider
    .otherwise('/');

    $stateProvider
    .state('stats', 
        {
            url: '/stats',
            templateUrl: './js/views/statsTmpl.html'
        })
    .state('table', 
        {
            url: '/table',
            templateUrl: './js/views/tableTmpl.html',
            controller: 'tableCtrl'
        });

});

在您的控制器中,您应该在使用前初始化您的 gridOptions。更好的是,尝试将此变量的设置提取到控制器范围,仅在异步方法中填充数据:

app.controller('tableCtrl', function($scope, tableService) {

    // Initialize gridOptions with all the properties, except for data
    $scope.gridOptions = {};
    $scope.gridOptions.columnDefs = [
        {name:'artist_id'},
        {name:'first_name'}
    ];
    $scope.gridOptions.data = [];

    var getAllArtistData = function() {

        tableService.getArtistData().then(function(data) {
            console.log("this is controller data", data);

            // fill only data in asynchronous callback
            $scope.gridOptions.data = data;
        });
    };
    getAllArtistData();
});

方法tableService.getArtistData() 异步执行,此方法的回调仅在从服务器检索数据时执行。这可能在几毫秒内发生,也可能在几分钟内发生。网格的渲染需要在回调执行之前发生,缺少如何渲染网格的元数据信息。这就是为什么我建议在启动异步调用之前初始化网格元数据,并且在回调中仅设置数据。