无法从json文件AngularJS中获取正确的数据

时间:2016-05-30 20:45:55

标签: javascript angularjs json

我的第一个AngularJS应用程序有问题。我正在使用自耕农发电机。我需要从json文件中获取数据并使用对象检查数组的长度。

我的data.json文件:

{"persons":[
    {  
         "firstname":"Christian",
         "lastname":"Bower",
         "age":21
      },
      {  
         "firstname":"Anthony",
         "lastname":"Martial",
         "age":25
      }
]}

我的角度控制器:

   'use strict';

        /**
         * @ngdoc function
         * @name webdevApp.controller:DataTableCtrl
         * @description
         * # DataTableCtrl
         * Controller of the webdevApp
         */
        angular.module('webdevApp')
          .controller('DataTableCtrl', function ($scope, $http) {
            this.awesomeThings = [
              'HTML5 Boilerplate',
              'AngularJS',
              'Karma'
            ];


            $http.get('../data.json').success(function(data){
                $scope.Data = data;
                $scope.namePerson = $scope.Data.persons[0].firstname;
            });

         console.log($scope.namePerson);
         console.log($scope.Data.length);
      });

控制台输出:

1) undefined

2)TypeError:无法读取未定义的属性“length”     在新的

下一个问题是 - 如何实现以下效果(带对象的数组)?

$scope.persons = [
    { 
        "firstname": "christian", 
        "lastname": "bower", 
        "age": 21
    },
    { 
        "firstname": "anthony1", 
        "lastname": "martial", 
        "age": 25 
    }];

2 个答案:

答案 0 :(得分:2)

// Router import { Router, browserHistory } from 'react-router' if (process.env.NODE_ENV === 'production') { // ... } else { // the hacky workaround Router.prototype.componentWillReceiveProps = function (nextProps) { let components = []; function grabComponents(routes) { routes.forEach((route) => { if (route.component) { components.push(route.component) } if (route.indexRoute && route.indexRoute.component) { components.push(route.indexRoute.component) } if (route.childRoutes) { grabComponents(route.childRoutes) } }) } grabComponents(nextProps.routes) components.forEach(React.createElement) // force patching } } 是异步调用,因此您必须在$http.get函数中输出结果,如下所示:

success

答案 1 :(得分:0)

$http.get来电是异步

将日志放入success功能。

$http.get('../data.json').success(function(data){
    $scope.Data = data;
    $scope.namePerson = $scope.Data.persons[0].firstname;

    //assign persons in scope
    $scope.persons = data.persons;

    //logs
    console.log($scope.namePerson);
    console.log($scope.Data.length);
});

请注意,恕我直言,您应该只在范围内指定data甚至persons,因为您可以从那里获得所有内容。将数千个无用的变量放在范围内会产生不必要的复杂性。