我的 REST 服务器正在从 /blog
返回以下内容:
["hello","yo"]
这是我的整个 angularjs 应用程序:
var myapp = new angular.module("myapp", ["ngResource"]);
myapp.controller("MainCtl", ["$scope", "$resource", function($scope, $resource){
var Blog = $resource("/blog/:entry", {entry: '@entry'});
$scope.entries = Blog.query();
}]);
当我输入{{entries}}
时在 html 的某处,我看到这个:[{"0":"h","1":"e","2":"l","3":"l","4":"o"},{"0":"y","1":"o"}]
不知何故, Angular 错误地解释了这个值数组。我也尝试过,结果完全相同:
myapp.controller("MainCtl", ["$scope", "$resource", function($scope, $resource){
var Blog = $resource("/blog/:entry", {entry: '@entry'}, {
list: {
url: "/blog",
method: "GET",
isArray: true,
transformResponse: function(data, headers) {
var h = ["hello","yo"];
console.log(h);
return h;
}
}
});
$scope.entries = Blog.list();
}]);
有趣的是,console.log
调用打印正确的值。
最佳答案
这绝对是 One dimensional array of strings being parsed to 2d by angular resource 的重复项
使用 $resource 时,如果 isArray = false,则预期响应是 JSON 对象:
{
"foo" : "bar"
}
如果 isArray = true,则预期响应应该是对象的 JSON 数组:
[
{ "foo" : "bar" },
{ "faa" : "bah" }
]
在这种情况下,您有三个选择:
- 使用 $http 而不是 $resource
- 使用 $http 的
transformResponse
功能(请参阅 http://docs.angularjs.org/api/ng .$http) - 如果您可以控制 API,则可以更改您发送的响应的结构。根据语义,您可以发送对象数组(使用
isArray=true
),或包含数组的对象(使用isArray=false
)。无论哪个对您来说更有意义。
关于javascript - angularjs资源查询误解数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356718/