Json 由角度资源解析为2d的一维字符串数组

Json 由角度资源解析为2d的一维字符串数组,json,angularjs,Json,Angularjs,以下是来自服务器的JSON响应 [ "hello", "world" ] 正在被此ngResource服务解析为2d数组 myService.factory('Name', function($resource){ return $resource(site_url+'api/accounts/:accountId/names/', {}, { list: {method:'GET', params:{}, isArray:true} }); }

以下是来自服务器的JSON响应

[
    "hello",
    "world"
]
正在被此ngResource服务解析为2d数组

myService.factory('Name', function($resource){
    return $resource(site_url+'api/accounts/:accountId/names/', {}, {
        list: {method:'GET', params:{}, isArray:true}
    });
});
这样叫

$scope.names = Name.list({accountId:$scope.account.id}, function(e){
    console.log(e);
});
追溯到

[{"0":"h","1":"e","2":"l","3":"l","4":"o"},{"0":"w","1":"o","2":"r","3":"l","4":"d"}]

有什么提示吗?

TLDRngResource在您的响应中需要一个对象或一组对象


当在操作列表中将
isArray
设置为
true
时,ngResource模块迭代响应中接收到的每个项目,并创建资源的新实例。为此,Angular在接收到的项目和
资源
类之间执行深度复制,这为我们提供了一个具有特殊方法的对象(
$save
$delete
等等)

检查一下

内部angular使用执行深度复制,此功能仅对对象数组进行操作,当我们传递字符串时,它会将其视为对象

JS中的字符串可以通过提供对每个字符的顺序访问来充当数组
angular.copy
在传递字符串时将生成以下内容

angular.copy('hi',{})   => {0:'h', 1:'i'}
每个字符都成为对象中的一个值,其索引设置为键ngResource将提供属性为
0
1
的资源


你的选择是:

使用较低级别的$http服务 在json响应中返回一个对象数组 截取响应并更改数据
如果您无法修改服务器发回的数据并希望使用ngResource,则需要转换响应。阅读《如何做》

我也一直在努力解决这个问题。下面是我的解决方案,通过使用query对服务进行微调

var app = angular.module('testApp', ['ngResource']);

app.factory('Name', function($resource, $sce) {
  var path = "test.json";

  return $resource(path, {}, {
    query: {
      method: 'GET',
      isArray: false
    }
  })
});

app.controller('testController', function($scope, Name) {
  $scope.result;

  $scope.getResult = function() {
    Name.query(function(data) {
      $scope.result = data;
    });
  };

  $scope.getResult();
});
HTML:

如果有兴趣,还可以使用Plunker:


希望这对某人有所帮助…

谢谢-如果我之前遇到过这一点:)谢谢,我花了12个小时寻找解决方案。多亏了你,我不会花25个小时:)。我返回一个对象,isArray被设置为false,但是我仍然有同样的问题。我通过仍然使用资源并按照您的建议从服务器端将其放入列表来修复它。
isArray:false
不工作,您需要将返回的字符串转换为对象检查此解决方案以了解如何转换响应,请参阅我的帖子:
[{'data': "hello"}, {'data': "world"}] 
var app = angular.module('testApp', ['ngResource']);

app.factory('Name', function($resource, $sce) {
  var path = "test.json";

  return $resource(path, {}, {
    query: {
      method: 'GET',
      isArray: false
    }
  })
});

app.controller('testController', function($scope, Name) {
  $scope.result;

  $scope.getResult = function() {
    Name.query(function(data) {
      $scope.result = data;
    });
  };

  $scope.getResult();
});
<!DOCTYPE html>
<html ng-app="testApp">

<head>

  <link href="style.css" rel="stylesheet" />
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-resource.min.js"></script>

  <script src="script.js"></script>
</head>

<body ng-controller="testController">
  <h1>{{result.surname}}</h1>

</body>

</html>
{
    "name": "Homer",
    "surname":  "Simpson",
    "Town": "Springfield"
}