$ http.get调用将错误数据返回到Angular UI-Grid控件

时间:2017-01-11 23:11:17

标签: javascript angularjs node.js angular-ui ui-grid

这是我的第一个使用ui-gridAngularJS nodejs框架作为后端的express应用程序。

API运行良好,数据正在流传,但我对事件的顺序以及对Angular上下文的异步$http.get()调用的使用感到困惑。

所以,我需要在屏幕上放置网格。此网格需要从API加载数据。这是html页面上的网格对象:

  <div class="tile-body" ng-controller="AdminUsersGridCtrl">
    <div id="grid" ui-grid="gridOptions" class="grid"></div>
  </div>

这是我的控制器:

app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {

    $http.get('/api/admin/user')
    .then(function (response) {

        $scope.myData = response;

        $scope.gridOptions = {
          data: 'myData',
          enableFiltering: true,
          columnDefs: [
            { field: 'firstName' },
            { field: 'lastName' },
            { field: 'jobTitle'},
            {
              field: 'email',
              filter: {
                condition: uiGridConstants.filter.ENDS_WITH,
                placeholder: 'ends with'
              }
            },
            {
              field: 'phone',
              filter: {
                condition: function(searchTerm, cellValue) {
                  var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
                  return strippedValue.indexOf(searchTerm) >= 0;
                }
              }
            },
          ]
        };
    }, 
    function (error) {
        console.log(error);
    });
  });

我在这个序列中遇到错误:

TypeError: Cannot read property 'data' of undefined
    at new <anonymous> (ui-grid.js:3130)
    at Object.invoke (angular.js:4604)
    at extend.instance (angular.js:9855)
    at nodeLinkFn (angular.js:8927)
    at angular.js:9231
    at processQueue (angular.js:15552)
    at angular.js:15568
    at Scope.$eval (angular.js:16820)
    at Scope.$digest (angular.js:16636)
    at Scope.$apply (angular.js:16928)

我不知道这里发生了什么。该错误消息来自哪里?

1 个答案:

答案 0 :(得分:3)

您应该在promise调用之外初始化gridOptions。

 app.controller('AdminUsersGridCtrl', function ($scope, $http, uiGridConstants) {


        $scope.gridOptions = {
          enableFiltering: true,
          columnDefs: [
            { field: 'firstName' },
            { field: 'lastName' },
            { field: 'jobTitle'},
            {
              field: 'email',
              filter: {
                condition: uiGridConstants.filter.ENDS_WITH,
                placeholder: 'ends with'
              }
            },
            {
              field: 'phone',
              filter: {
                condition: function(searchTerm, cellValue) {
                  var strippedValue = (cellValue + '').replace(/[^\d]/g, '');
                  return strippedValue.indexOf(searchTerm) >= 0;
                }
              }
            },
          ]
        };

     $http.get('/api/admin/user')
    .then(function (response) {
       $scope.gridOptions.data = response.data;  // Content is in the response.data
    },
    function (error) {
        console.log(error);
    });
  });