我有以下代码,一个消耗 API 休息的工厂:
angular.module('teachers')
.factory("TeachersService",
function($resource) {
var restPath = 'http://localhost:8001/entities/teacher/';
return $resource(restPath + ':id', { id: "@teacherId" }, {
'getSubjects': {
method: 'GET',
url: restPath + ':id' + '/subject',
isArray: true
},
'update': { method: 'PUT'},
'getClasses': {
method: 'GET',
url: restPath + ':id' + '/class',
isArray: true
}
});
});
在控制器中,我使用工厂:
vm.teacher = TeachersService.get({id: vm.teacherId}, function() {
console.log(vm.teacher)
}, function() {
console.log('Teacher not found')
vm.teacher = null;
})
数据检索得很好,但现在我需要更新这个实体的数据,我想使用工厂有的更新方法:
vm.teacher.$update(function() {
console.log('success')
}, function(error){
console.log('error')
console.log(error)
});
但我不知道为什么它总是让我失败(这些方法适用于 curl 和其他程序,如邮递员)。
这是失败标头的示例:
对象{数据:空,状态:-1,标题:fd/<(),配置:对象,状态文本:“”}
我不明白发生了什么,我认为问题出在我传递 id 的方式上。我确定实体vm.teacher
有teacherId
一个整数值,但我不知道为什么没有通过。另外,我看到了 Firefox 的网络控制台(在我的情况下),我看到对服务器的调用不存在,但是当我将定义更改为 id 时,例如:
{ id: "@_teacherId" }
调用完成但出现错误,因为 url 最后没有实体标识符,而 PUT 方法中的服务器需要它。
假用户的一个例子是(在得到它之后):
Object { createdBy: 1, phone: "+34740 51 73 72", createdAt: "Tue Oct 25 12:58:30 2016", name: "Alvaro", address: "Callejón Lourdes Pozuelo 11 Apt. 54…", teacherId: 4, $promise: Object, $resolved: true }
任何想法?我被屏蔽太多次了。
谢谢!
编辑
如果我更改代码并设置 GET 方法调用它:
'update': {
method: 'GET',
url: restPath + ':id'
}
但不是当方法是 PUT 时:
'update': {
method: 'PUT',
url: restPath + ':id'
}