【问题标题】:cannot access objects inside service response无法访问服务响应中的对象
【发布时间】:2017-01-28 03:44:10
【问题描述】:

当我尝试访问 JSON 响应时,我无法访问该对象。

我需要获取targetdatapoint 对象,然后我需要迭代dataPoint 数组。

result.target 在上述情况下是未定义的。

控制器:

$scope.serviceCalls = function() {
    var serviceUrl = "http://localhost:8080/rest/1";
    var promise = CommonService.getServiceJSON(serviceUrl);
    promise.then(function(result) {
        $scope.jsondata = result;
        console.log($scope.jsondata); // getting the JSON in console logs
        console.log($scope.jsondata.target); //returns undefined 
    }, function(reason) {
        alert('Failed: ' + reason);
    }, function(update) {
        alert('Got notification: ' + update);
    });
}

我收到的 JSON 响应:

[{
    "target": "xxxxxxxxxxxx",
    "datapoints": [
        [14711037952.0, 1474340220],
        [14711058432.0, 1474340280],
        [14719434752.0, 1474361700],
        [null, 1474361760]
    ]
}]

【问题讨论】:

  • $scope.jsondata[0].target - 结果是一个数组。还要确保结果是 Json 而不是字符串(否则使用 JSON.parse(result) 解析它)
  • 谢谢。我错过了它是一个数组 JSON 的事实。

标签: javascript html angularjs json rest


【解决方案1】:

响应是一个数组,所以你必须使用索引。

例子

console.log($scope.jsondata[0].target);

【讨论】:

    【解决方案2】:

    试试$scope.jsondata = JSON.parse(result);

    【讨论】:

      【解决方案3】:

      $scope.jsondata 是一个数组

      $scope.jsondata[0].target will give you target
      $scope.jsondata[0].datapoints will give you required array
      

      【讨论】:

        【解决方案4】:

        使用索引来遍历数据:

        $scope.jsondata[0].target

        【讨论】:

          猜你喜欢
          • 2017-10-25
          • 2018-01-03
          • 2021-08-24
          • 2017-01-26
          • 1970-01-01
          • 2015-12-14
          • 1970-01-01
          • 1970-01-01
          • 2022-12-31
          相关资源
          最近更新 更多