goldylucks
goldylucks

Reputation: 6144

angularJS $resource response is both array AND object

got this json file:

[
{
    "name": "paprika",
    "imgSrc": "img/paprika.jpg"
},
{
    "name": "kurkku",
    "imgSrc": "img/kurkku.jpg"
},
{
    "name": "porkkana",
    "imgSrc": "img/porkkana.jpg"
},
{
    "name": "lehtisalaatti",
    "imgSrc": "img/lehtisalaatti.jpg"
},
{
    "name": "parsakaali",
    "imgSrc": "img/parsakaali.jpg"
},
{
    "name": "sipula",
    "imgSrc": "img/sipuli.jpg"
},
{
    "name": "peruna",
    "imgSrc": "img/peruna.jpg"
},
{
    "name": "soijapapu",
    "imgSrc": "img/soijapapu.jpg"
},
{
    "name": "pinaatti",
    "imgSrc": "img/pinaatti.jpg"
}
]

Which I successfully fetch in a factory:

factory('getJson', ['$resource', function($resource) {
    return $resource('json/vegs.json', {}, {
      query: {method:'GET', isArray:true}
    });
  }]);

in my Controller I can get the json's file content:

var vegs = getJson.query();
    $scope.vegs = vegs;
    console.log(vegs)
    console.log(typeof vegs)

The weird part is the first console.log produces an array of objects, as expected. The second console says it's an "object", and not an array.

I can get the .json content to my view using {{vegs}}, and I can use ng-repeat as well, tho in the controller I can't do vegs[0] or vegs.length. It comes out empty.

I'm breaking my head on this for over 3 hours now :)

Upvotes: 0

Views: 397

Answers (1)

smw
smw

Reputation: 1033

This isn't an 'answer'. Just an observation on one part of your issue. (Sorry, can't comment yet...new to stackoverflow).

Just a note on your comment that "The second console says it's an "object", and not an array." Using typeof on an array will always return "object".

There are various (and debated, it seems) ways to test if it's an array--Array.isArray(obj) for example.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

Upvotes: 1

Related Questions