【发布时间】:2016-07-20 16:23:53
【问题描述】:
在我的应用程序中,我有一个表单,用户可以在其中添加多条记录。加载页面后,我需要发出 GET 请求来检查数据库中的现有记录。如果存在记录,我会在页面上填充它们。那里没问题。
我遇到的问题是当数据库没有现有记录时,服务器返回 204 No Content。在控制器中,成功函数仍然被执行,但没有数据,只有 $promise 对象和 $resolved: true。
代码如下:
工厂:
return $resource (
https://my.backend/api/records/:id",
{},
{
"getExistingRecords": {
method: 'GET',
isArray: false,
params: {id: '@id'},
withCredentials: true}
}
)
控制器:
function initialize(id){
alertFactory.getExistingRecords({id: id})
.$promise
.then(function (records){
if(records){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
},function(error){
Notification.error(error);
});
}
initialize(id);
当服务器返回“204 No Content”时,我从控制台得到这个
处理此问题的唯一方法是检查记录对象的对象属性吗?
例如:
function initialize(id){
alertFactory.getExistingRecords({id: id})
.$promise
.then(function (records){
if(records.recordName){
$scope.existingRecords = records;
}else {
$scope.existingRecords = {};
}
},function(error){
Notification.error(error);
});
}
initialize(id);
还是我错过了什么?
【问题讨论】:
-
在您的 $resource 定义中,
isArray不应该是true吗?在空响应的情况下,您的服务器可能会返回一个空数组而不是“204 无内容”。至少命名动作 getExistingRecords() 有点暗示它应该是一个数组.. -
您可以随时检查记录是否存在,并且它的长度大于 0...
标签: javascript angularjs