jsonangularjsspringngresource

Unable to retrieve JSON array with AngularJS $resource


I've been trying retrieve values from JSON and so far, been unsuccessful. It does get called on the front-end when I refresh the page, but the information is not passing to the next method. I think the issue might be down to the promises.push... line, as I've tried to debug the method underneath and the information is not being passed on at all.

AngularJS:

var promises = [];
promises.push(SpringDataRestService.get({"collection": "subjects"}).$promise);

// Require each of these queries to complete before continuing
$q.all(promises).then(function (data) {
    // Grab the first result
    $scope.available = data[0].subjects;
    $scope.selected = [];
    // If this is an update, get the second result in set
    if (data.length > 1) {
        // For each permission that is assigned to this role, add ID (name) to selected
        for (var i = 0; i < data[1].data.subjects.length; i++) {
            var perm = data[1].data.subjects[i];
            $scope.selected.push(perm.name);
        }
    }
    $scope.tableEditOptions = new NgTableParams({}, {
        dataset: $scope.available
    });
   $scope.available, 'name');
}).catch(function (data) {
  // ERROR
});

JSON:

[
  {
    "name": "FWGWG",
    "description": "WGWGWG",
    "lockId": 0
  },
  {
    "name": "QFQFQF",
    "description": "QFQFQFQ",
    "lockId": 0
  }
]

I'm confident as well my for loop is wrong due to assigning the values as well, since I don't think it should be data.subjects, but I understand these threads are only 1 issue per question. Any help would be greatly appreicated.


Solution

  • Use the query method for arrays:

    var promise = SpringDataRestService.query({"collection": "subjects"}).$promise;
    
    promise.then(function (dataArr) {
        console.log(dataArr);
        //...
    }).catch(function (errorResponse) {
        console.log(errorResponse);        
    });
    

    With the REST services, the get method returns a JavaScript object and the query method returns a JavaScript array.

    From the Docs:

    $resource Returns

    A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

    {
      'get':    {method: 'GET'},
      'save':   {method: 'POST'},
      'query':  {method: 'GET', isArray: true},
      'remove': {method: 'DELETE'},
      'delete': {method: 'DELETE'}
    }
    

    ...

    It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

    For more information, see