我从服务器返回一组对象:
[{id: 1, name: "name"},{id: 2, name: "name2"}]
现在我使用angular-resource $query
来获取数据,因为它需要一个数组。
收到数据后,我收到此错误:
TypeError: value.push is not a function
我从server =?
提供的响应是否存在问题错误来源:
// jshint +W018
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
if (typeof item === "object") {
value.push(new Resource(item));
} else {
// Valid JSON values may be string literals, and these should not be converted
// into objects. These items will not have access to the Resource prototype
// methods, but unfortunately there
value.push(item);
}
});
} else {
shallowClearAndCopy(data, value);
value.$promise = promise;
}
}
控制器:
var stream = [];
stream = new VideoStream({param: 'streamTypes'});
stream.$query();
服务:
app.service('DataService', [
'$resource', 'Common', '$rootScope',
function($resource, Common, $rootScope) {
return $resource($rootScope.appWebRoot + "myUrl/:param", {param: '@param'},
{
});
}
]);
视频流:
app.service('VideoStream', [
'$resource', 'Common', '$rootScope',
function($resource, Common, $rootScope) {
return $resource($rootScope.appWebRoot + "videoStreams/api/:param",
{param: '@param'},
{
});
}
]);
答案 0 :(得分:9)
您遇到的问题是您正在创建资源实例作为对象
var stream = [];
stream = new VideoStream({param: 'streamTypes'}); //This is the problem. $resource is expecting an array.
stream.$query(); //This is an instance method.
//All you need to do is:
var stream = [];
stream = VideoStream({param: 'streamTypes'}).query();
来自https://docs.angularjs.org/api/ngResource/service/$resource:
$ resource returns:
资源“类”对象,其中包含默认资源集的方法 可选择使用自定义操默认设置 包含这些行动:
{ 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} };
调用这些方法使用指定的http方法调用$ http, 目的地和参数。从服务器返回数据时 那么该对象就是资源类的一个实例。行动 保存,删除和删除可用作$的方法 前缀
答案 1 :(得分:1)
类对象或实例对象上的操作方法可以是 使用以下参数调用:
- HTTP GET“class”操作:Resource.action([parameters],[success],error])
- 非GET“类”操作:Resource.action([parameters],postData,[success],[error])
- 非GET实例操作:实例。$ action([参数],[成功],[错误])
在检查控制器中VideoStream
的值时,我们发现:
function Resource(value) {
shallowClearAndCopy(value || {}, this);
} // Actual Resource class object with regular action(s) we can work with
那里
致电VideoStream({param: 'streamTypes'})
返回:
undefined // Cannot call anything of undefined
和new VideoStream({param:'streamTypes'})
返回:
Resource {param: "streamTypes"}
// Instance of the Resource class (an object) where $action(s) are available
// Verified in the chrome console
考虑到这一点,案例应该是:
var stream = [];
stream = VideoStream.query({param: 'streamTypes'});