[英]How to manipulate data from ngResource query() before returning it?
I'm trying to comprehend how can I modify data that $resource.query()
returns which - as it turned out - is not really Promise from $q
but an empty object/array to be filled when async call is done.我试图理解如何修改
$resource.query()
返回的数据 - 事实证明 - 并不是来自$q
真正承诺,而是在异步调用完成时要填充的空对象/数组。
I defined a service where I'd like to modify data that came from $resource
(filter it to be precise), but nothing gets actually filtered.我定义了一个服务,我想在其中修改来自
$resource
数据(精确过滤),但实际上没有过滤任何内容。 I get whole array back.我取回整个阵列。
I'm sure there is some trivial thing I'm missing here.我确定我在这里遗漏了一些微不足道的东西。 Thanks for help in advance.
提前感谢您的帮助。
Here's the service (Employee is the $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);
}
};
}
]);
EDIT编辑
By ippi suggestion I also tried accessing underlying promise:根据 ippi 的建议,我还尝试访问基础承诺:
var query = function(id) {
return Employee.query().$promise
.then(function(data) {
return findByManager(data, id);
});
};
return {
query: query,
}
In controller:在控制器中:
$scope.employees = Report.query(id);
But it returns object instead of an array.但它返回对象而不是数组。
I'm not sure if this is the complete answer you are looking for, but it should help:我不确定这是否是您正在寻找的完整答案,但它应该会有所帮助:
Employee.query({...}) is not a promise itself but you CAN access the raw $http promise like this: Employee.query({...}) 本身不是承诺,但您可以像这样访问原始的 $http 承诺:
Employee.query({...}).$promise.then(function(result){
console.log(result);
});
($resource is just a wrapper around $http.) ($resource 只是 $http 的包装器。)
And if you don't mind me saying so, the idea of filtering your resources on the client-side the second you retrieve them does sound as if it works against the idea with API-resources to begin with.如果您不介意我这么说,那么在您检索资源的第二个瞬间在客户端过滤资源的想法听起来似乎与 API 资源的想法相悖。 Requesting a subset of "Employees" sure sounds like an API-feature and should probably be implemented on the server-side.
请求“员工”的子集听起来确实像是 API 功能,应该在服务器端实现。 I'd say you'd want to call your resource like:
我会说你想像这样调用你的资源:
Employee.query({ managerId: employee.employeeId });
Alright, I scrapped your Report
-factory (sorry!) and ended up with:好吧,我报废了你的
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">
It seems like this could be an acceptable answer as well: https://stackoverflow.com/a/28907040/1497533这似乎也是一个可以接受的答案: https : //stackoverflow.com/a/28907040/1497533
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.