如何在没有数据的情况下处理已解析的$promise

How to handle a resolved $promise with no data

本文关键字:promise 处理 情况下 数据      更新时间:2023-09-26

在我的应用程序中,我有一个表单,用户可以在其中添加多条记录。当页面被加载时,我需要发出一个GET请求来检查DB中的现有记录。如果存在记录,我会在页面上填充它们。没问题。

我遇到的问题是,当DB没有现有记录时,服务器会返回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无内容"时,我从控制台得到这个

控制台图像

处理此问题的唯一方法是检查记录对象的对象属性吗?

例如:

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);

还是我错过了什么?

如果您能获得带有响应的状态代码,那会更好。没有直接的方法。但你可以使用拦截程序来解决问题:

var resource = $resource(url, {}, {
    get: {
        method: 'GET'
        interceptor: {
            response: function(response) {      
                var result = response.resource;        
                result.$status = response.status;
                return result;
            }
        }
    }                            
});

现在你可以:

                if(records.$status === 200){
                    $scope.existingRecords = records;
                }else {
                    $scope.existingRecords = {};
                }

如果没有寄存器,我认为应该返回一个空列表。