我的资源对象如下所示:
.factory('StudentWebService', ['$resource',function($resource){
return $resource( baseUrl + 'students/:_id', { _id: '@_id'},
{
save: { method: 'POST', isArray: true}
}
}])
现在使用如下资源:
var studentObj = new StudentWebService();
studentObj.name = 'john';
studentObj.age = '12';
studentObj.$save()
.then(function(res) { console.log('i never get called'); })
当执行上面的代码时,保存功能起作用,即数据保存在服务器上,而不是" .then"中的回调函数。没有被调用,控制台显示以下错误:
TypeError: undefined is not a function
at http://xxx/angular.js?version=1411563643:21994:25
at Array.forEach (native)
at forEach (http://xxx/angular.js?version=1411563643:323:11)
at angular.module.factory.Resource.(anonymous function).$http.then.value.$resolved (http://xxx/angular.js?version=1411563643:21993:17)
当我在angular.js中访问21994行时,我看到了这个:
if (data) {
// Need to convert action.isArray to boolean in case it is undefined
// jshint -W018
if (angular.isArray(data) !== (!!action.isArray)) {
throw $resourceMinErr('badcfg', 'Error in resource configuration. Expected ' +
'response to contain an {0} but got an {1}',
action.isArray?'array':'object', angular.isArray(data)?'array':'object');
}
// jshint +W018
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item)); //THIS IS LINE 21994
});
} else {
shallowClearAndCopy(data, value);
value.$promise = promise;
}
}
作为响应,服务器返回一个数组。
编辑:还有很多事情需要注意。当服务器返回一个Object并且没有定义isArray时。上面的代码工作正常。
有人能指出我错过的方向吗?
(请注意我暂时已找到解决方法,但我想在此处了解此问题。这是我的解决方法:
var studentObj = {};
studentObj.name = 'john';
studentObj.age = '12';
StudentWebService.save(studentObj,function(res){
//this call gets called and works fine
});