You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS 1.6读取JSON文件返回undefined数组问题排查

问题排查:AngularJS 1.6 $http获取数据后返回undefined数组的原因及解决方法

Hey there, let's break down why you're getting that array of undefined values instead of the platform names you're expecting.

问题根源

When you use $http in AngularJS 1.6, the success callback inside .then() receives a response object, not the raw JSON data directly. This response object includes properties like data, status, config, headers, and more — total of 6 properties, which lines up with your 6 undefined entries.

In your code, you're looping over the entire response object with angular.forEach(jsonData, function (item) { ... }). Since none of those response properties have a platform key, every item.platform call returns undefined, hence the array you see in the console.

解决方案

You need to access the actual JSON data via the response object's data property. Here's the fixed controller code:

'use strict';
var app= angular.module('app');
app.controller('MainController',['$scope', '$http', MainController]);
function MainController ($scope, $http) {
  // REQUEST OPTIONS USING GET METHOD.
  var request = {
    method: 'get',
    url: 'data.json',
    dataType: 'json',
    contentType: "application/json"
  };
  $scope.arrSeries = []; // Using [] is cleaner than new Array()
  $http(request)
  .then(function onSuccess(response) {
    // Access the actual dataset from response.data
    angular.forEach(response.data, function (item) {
      $scope.arrSeries.push(item.platform);
    });
    console.log($scope.arrSeries); // Now logs ['web-desktop','android','ios']
  }).catch(function onError(request) {
    console.log("not found");
  });
}

额外小优化

  • Initializing an empty array with [] is more idiomatic in JavaScript than new Array().
  • You can simplify the $http call even further for GET requests targeting JSON (AngularJS auto-parses JSON responses):
$http.get('data.json')
.then(function onSuccess(response) {
  angular.forEach(response.data, function (item) {
    $scope.arrSeries.push(item.platform);
  });
  console.log($scope.arrSeries);
}).catch(function onError() {
  console.log("not found");
});

That should give you exactly the platform name array you're aiming for!

内容的提问来源于stack exchange,提问作者Atom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:46:04