Search code examples
angularjsngresource

$resource, Data.query({other_id: 1}) is retrieving all the data


I have some information in a rest api:

{
    'id': 1,
    'name': 'test',
    'other_id': 1
},
{
    'id': 2,
    'name': 'test2',
    'other_id': 1
},
{
     'id': 3,
     'name': 'test3',
     'other_id': 2
}

I try using Data.query({other_id: 1}) and Data.query({'other_id': 1}) but both retrieve the 3 rows and I want the first and the second row

What am I doing wrong?


Solution

  • You will want to use the $resource get method instead of query. Query will return a collection, while get returns a single element.

    An example from the docs:

    var User = $resource('/user/:userId', {userId:'@id'});
    var user = User.get({userId:123});
    

    Edit

    Query cannot return a subset of the collection, it returns the entire collection served by your endpoint. In order to get a subset of the objects in a collection, you have two options:

    1. Modify your backend endpoint to expect a list of ids, and only return those objects who have a matching id.

      var data = Data.query({ids:'1,2'});
      
    2. Get all the objects, and simply filter the irrelevant ones out.

      var desiredObjects = [1,2];
      Data.query().then(function(data) {
          data.filter(function(a) {
              return desiredObjects.indexOf(a.id) > -1
          });
      });