资源工厂:
.factory('WorkerRepository', function($resource){
return $resource('workers/:id', {id:'@id'});
})
控制器:
.controller('ListController', function($scope, WorkerRepository){
var workers = WorkerRepository.query(function(){
$scope.workers = workers;
});
$scope.worker = {nameSurname: 'Peter', email: "test@gmail.com", phone: 600100200};
$scope.add = function() {
var worker = new WorkerRepository(this.worker);
worker.$save();
};
})
执行$scope.add
方法时,脚本会抛出TypeError: Object #<g> has no method 'push'
错误。如果我理解正确$resource
,默认情况下$save
方法仅提供'save': {method:'POST'},
,因此没有isArray: true
。那我为什么会收到这个错误?
答案 0 :(得分:2)
显然,错误在我的后端REST控制器中撒谎(感谢提示@Stewie!) - 我没有将POST方法与操作相关联,因此$save()
方法正在调用对query()
负责的操作,它确实返回一个对象数组。
当时:
query() -> GET /workers -> return array of workers
save() -> POST /workers -> return array of workers
后端控制器重构:
query() -> GET /workers -> return array of workers
save() -> POST /workers -> return created worker