【问题标题】:How to handle a resolved $promise with no data如何处理没有数据的已解决 $promise
【发布时间】: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”时,我从控制台得到这个

Console Image

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

例如:

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


【解决方案1】:

如果你能得到带有响应的状态码就更好了。没有直接的方法。但是你可以workaround 使用拦截器:

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 = {};
                }

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2017-10-24
      • 1970-01-01
      • 2019-02-18
      相关资源
      最近更新 更多