angularjsangular-resourcengresourceangularjs-ng-resource

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.

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. 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):

  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:

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.


Solution

  • 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({...}).$promise.then(function(result){
        console.log(result);
    });
    

    ($resource is just a wrapper around $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. Requesting a subset of "Employees" sure sounds like an API-feature and should probably be implemented on the server-side. I'd say you'd want to call your resource like:

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

    Edit:

    Alright, I scrapped your Report-factory (sorry!) and ended up with:

    // 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