了解 angularJS $resource isArray 属性

Understanding angularJS $resource isArray property

我正在学习 angular 的 $resource 服务,并且在 angular tutorial 中添加了一个自定义操作(查询),其中设置了 方法 'get' 并且 isArray 设置为 true

return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
 });

但是,如果您查看 the docs for $resource,'query' 操作已经将其 方法 设置为 'get' 和 isArray 已被 default 设置为 true。所以我认为我可以将这些属性排除在外。

这适用于 方法 属性,但事实证明,如果我省略 isArray 属性 我得到这个错误:

Error: [$resource:badcfg] Error in resource configuration for action query. Expected response to contain an object but got an array

这是为什么?

我认为您误解了文档。

默认不添加任何自定义操作,支持以下:

'get':    {method:'GET'},
'save':   {method:'POST'},
'query':  {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} 

因此,默认情况下,query 操作期望一个数组被 returned,这是有道理的,因为查询通常会 return 一个项目数组。

所以如果你使用:

phonecatServices.factory('Phone', ['$resource', function($resource){
    return $resource('phones/phones.json');
}]);

然后您可以像这样执行查询:

var queryParams = { name: 'test' };

Phone.query(queryParams, {}, function (response) {
    $scope.phones = response;
});

现在,如果您想添加自定义操作,那么 isArray 的默认值是 false,因此:

return $resource('phones/:phoneId.json', {}, {
      someCustomAction: {method:'GET', params:{phoneId:'phones'} }
});

需要return一个对象。如果一个数组被 returned 那么 isArray 需要被设置为 true 像这样:

return $resource('phones/:phoneId.json', {}, {
      someCustomAction: {method:'GET', params:{phoneId:'phones'}, isArray: true }
});