【发布时间】:2015-08-20 01:56:28
【问题描述】:
我知道这个问题已经存在于 SO 上(如这里:Error in resource configuration. Expected response to contain an object but got an array),即使我几天前已经遇到过这个错误,我也没有找到为什么我现在得到它。
一方面,我在Node Express 中有一个 RESTful API。它使我可以访问数据库,我试图在其中获取一些数据。当使用特定的$resourcerequest 时,我得到了这个 JSON(用 Postman 测试):
[
{
"ref": 2,
"type": "string here",
"matriculeMD": 4567,
"name": "William",
"date": "2016-09-14T22:00:00.000Z",
"client": 1
},
{
"ref": 4,
"type": "string here",
"matriculeMD": 1589,
"name": "Averell",
"date": "0000-00-00",
"client": 1
}
]
另一方面,我有一个 Angular JS 应用程序。这个使用工厂从 API 获取数据:
.factory('Things', ['$resource', function($resource) {
return $resource(
'api_url/:client_id',
{client_id: '@client_id'}, // getting some data from an ID
{'query' : {
method : 'GET', // ofc, it's a get request in the API
isArray : false // to be sure to get an object and not an array
}
}
我还有一个使用这个工厂的控制器,尝试使用参数执行查询:
app.controller('ctrl', ['$scope','Things', function ($scope,$things)
{
$scope.thing = $things.query({},{'client_id':'1'});
// replacing '@client_id' from factory with 1. I also tried with quoteless 1.
}
]);
最后,我有一个 html 视图,我尝试使用我应该在 $scope.thing 中获取的数据和一些 <div ng-repeat'thing in things'>{{thing.ref}}</div>。
通过阅读其他帖子,我确信将isArray : false 添加到工厂可以解决问题,因为它已经在另一家工厂修复了它。
有什么想法吗?
编辑:感谢您的回复。我改变了我的工厂代码:
.factory('Things', ['$resource', function($resource) {
return $resource(
'api_url/:client_id',
{client_id: '@client_id'}, // getting some data from an ID
{'query' : {
method : 'GET', // ofc, it's a get request in the API
isArray : true //
}
}
它修复了错误。现在,我正在处理我的$scope 内容未定义的另一个问题并发送$promise : Promise, $resolved : Resolved。我阅读了$resource 文档以了解它的含义,但我仍然不知道如何使它工作。
【问题讨论】:
-
那么您的 API 到底返回了一个数组? isArray 不会转换数据,它只是告诉 Angular 期望的数据结构。
标签: javascript json angularjs