Search code examples
javascriptangularjsngresource

How to get first element of array returned by Angular resource?


I got response from server with $resource. In console it shows like:

$promise: Object,
$resolved: true,
0: f

How can I get that 0 element? When I try array[0] syntax I get undefined.

Here is my $resouce code:

angular.module('groupsModel', ['ngResource']).
    factory('Groups', function($resource) {
        var Groups = $resource('http://localhost:7777/api/users/:id/bands', {id:'@id'}, {'query':  {method:'GET', isArray:true, params: {id:'@id'}}});

        return Groups;
    });

Solution

  • To get resource you can do this

    groupsModel.query()
    

    because you named your first resource 'query'

    and to get promise of this resource you can do

    groupsModel.query().$promise
    

    and to use data returned from the resource you can do

    groupsModel.query().$promise.then(function(data){
    // success, use data
    }, function(err){
    // failure, use err for logging etc...
    });