字符串的一维阵列被解析由角资源到2d [英] One dimensional array of strings being parsed to 2d by angular resource
问题描述
从服务器以下JSON响应
The following JSON response from the server
[
"hello",
"world"
]
本ngResource服务被解析成一个二维数组
is being parsed into a 2d array by this ngResource service
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"}]
任何提示?
推荐答案
TLDR; ngResource 预计,对象或数组的的对象的在您的答复。
TLDR; ngResource expects an object or an array of objects in your response.
在 IsArray的
设置为真正
在操作列表,在 ngResource 在每个项目模块迭代在响应接收到的和它创建一个资源的新实例。要做到这一点角度,基于接收到的项目,并在资源
类之间的深拷贝,这给了我们一个对象,具有特殊方法( $保存
, $删除
等)
When isArray
is set to true
in the list of actions, the ngResource module iterates over each item received in the response and it creates a new instance of a Resource. To do this Angular performs a deep copy between the item received and the Resource
class, which gives us an object with special methods ($save
, $delete
and so on)
这里检查源。
Check the source here.
在内部角度使用 angular.copy 执行深拷贝和这个功能只有对象和阵列,当我们传递一个字符串,它将把它当作一个对象。操作
Internally angular uses angular.copy to perform the deep copy and this function only operates with objects and arrays, when we pass a string, it will treat it like an object.
在JS字符串可以通过提供每个字符的顺序访问表现为数组。 angular.copy
将产生如下当传递一个字符串
Strings in JS can behave as arrays by providing sequential access to each character. angular.copy
will produce the following when passed a string
angular.copy('hi',{}) => {0:'h', 1:'i'}
每个字符成为对象的值,其指数设定为关键。 ngResource 将提供性能资源 0
和 1
。
Each character becomes a value in an object, with its index set as the key. ngResource will provide a resource with properties 0
and 1
.
您的选择是:
$http.get('/res').success(function(data){
$scope.test = data;
});
返回对象的数组,在你的JSON响应
[{'data': "hello"}, {'data': "world"}]
拦截响应,并改变你的数据
如果您不能修改服务器返回的数据,并要使用 ngResource 您将需要转换的响应。了解如何做到这一点href=\"http://docs.angularjs.org/api/ng.%24http\">
Intercept the response and change your data
If you cannot modify the data the server sends back and want to use ngResource you will need to transform the response. Read how to do it here
这篇关于字符串的一维阵列被解析由角资源到2d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!