gpt4 book ai didi

angularjs - 理解 angularJS $resource isArray 属性

转载 作者:行者123 更新时间:2023-12-03 06:54:16 24 4
gpt4 key购买 nike

我正在学习 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默认设置为 true。所以我想我可以把这些属性排除在外。

这适用于 method 属性,但事实证明,如果我省略 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 操作期望返回一个数组,这是有道理的,因为查询通常会返回一个项目数组。

所以如果你使用:

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'} }
});

需要返回一个对象。如果返回一个数组,则需要将 isArray 设置为 true,如下所示:

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

关于angularjs - 理解 angularJS $resource isArray 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28498588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com