【问题标题】:How to manipulate data from ngResource query() before returning it?如何在返回之前从 ngResource query() 操作数据?
【发布时间】:2016-09-03 18:10:44
【问题描述】:

我试图理解如何修改 $resource.query() 返回的数据 - 结果证明 - 不是来自 $q 的真正 Promise,而是在异步调用完成时要填充的空对象/数组。

我定义了一项服务,我想在其中修改来自$resource 的数据(准确地过滤它),但实际上没有过滤任何内容。我得到了整个数组。

我确定我在这里遗漏了一些琐碎的事情。提前感谢您的帮助。

这里是服务(员工是$resource):

  factory('Report', ['Employee',
        function(Employee) {

            var query = function(id, cb) {
                return Employee.query({}, function(data) {
                    return cb(data, id);
                });
            };

            var findByManager = function(employees, employeeId) {
                return employees.filter(function(element) {
                    console.log(element);
                    return employeeId === element.managerId;
                });

            };

            return {
                query: function(employee) {
                    return query(employee.employeeId, findByManager);
                }
            }; 
        }
  ]);

编辑

根据 ippi 的建议,我还尝试访问底层承诺:

var query = function(id) {
            return Employee.query().$promise
                .then(function(data) {
                    return findByManager(data, id);
                });
        };

return {
    query: query,
}

在控制器中:

$scope.employees = Report.query(id);

但它返回的是对象而不是数组。

【问题讨论】:

    标签: angularjs angular-resource ngresource angularjs-ng-resource


    【解决方案1】:

    我不确定这是否是您正在寻找的完整答案,但它应该会有所帮助:

    Employee.query({...}) 本身不是一个承诺,但您可以像这样访问原始的 $http 承诺:

    Employee.query({...}).$promise.then(function(result){
        console.log(result);
    });
    

    ($resource 只是 $http 的包装。)

    如果您不介意我这么说,那么在您检索资源的那一刻就在客户端过滤资源的想法听起来确实与 API 资源的想法背道而驰。请求“员工”的一个子集听起来确实像一个 API 功能,并且可能应该在服务器端实现。我会说你想调用你的资源:

    Employee.query({ managerId: employee.employeeId });
    

    编辑:

    好的,我取消了您的 Report-factory(对不起!)并最终得到:

    // Controller
    $scope.id = 1; // Or something...
    $scope.employees = Employee.query();
    
    // Html
    <tr ng-repeat="employee in employees | filter: {employeeId: id} : true | orderBy:id">
    

    这似乎也是一个可以接受的答案:https://stackoverflow.com/a/28907040/1497533

    【讨论】:

    • 感谢您的回复。但问题是:如果我只是从 then() 方法内部返回 findByManager,它会起作用吗?
    • 关于“在客户端过滤资源”。我实际上为此实现了 API,但我认为由于我已经在客户端上缓存了需要从中获取子集的数据,因此简单地过滤而不是为每个 employee.employeeId 发出全新的请求会更加高效。我错了吗?
    • 在您的编辑中,您对.then(function(data) { 有任何回应吗?由于它是一个 $http 请求,它可能看起来像 `data.data = [ { ... }, { ... }, ... ]
    • 你必须返回一些东西。 var query = function(id) { return Employee....
    • 你是对的。不幸的是,它返回对象而不是数组。
    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    相关资源
    最近更新 更多