Search code examples
angularjsngresource

AngularJS query works with http, but not work with resource


I try to use many answers about that but they did not work.

I am am using an api to get json data with AngularJS.

I can get data with $http and bind it to front end. But i can not get same data with $resource.

When i try to get data with ngResource ($resource) , it gives error like that :

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object

For example, i use this project and you can check the project from here : https://github.com/okproject/AngularGetPost

Can you help me please ?

Result data like :

{
geonames: [
{
continent: "EU",
capital: "Andorra la Vella",
languages: "ca",
geonameId: 3041565,
south: 42.42849259876837,
isoAlpha3: "AND",
north: 42.65604389629997,
fipsCode: "AN",
population: "84000",
east: 1.7865427778319827,
isoNumeric: "020",
areaInSqKm: "468.0",
countryCode: "AD",
west: 1.4071867141112762,
countryName: "Andorra",
continentName: "Europe",
currencyCode: "EUR"
},
{
continent: "AS",
capital: "Abu Dhabi",
languages: "ar-AE,fa,en,hi,ur",
geonameId: 290557,
south: 22.633329391479492,
isoAlpha3: "ARE",
north: 26.08415985107422,
fipsCode: "AE",
population: "4975593",
east: 56.38166046142578,
isoNumeric: "784",
areaInSqKm: "82880.0",
countryCode: "AE",
west: 51.58332824707031,
countryName: "United Arab Emirates",
continentName: "Asia",
currencyCode: "AED"
}
]
}

Solution

  • Tried, and got it working, the thing is the call you are making is returning an object, not an array:

    {"geonames":[{"continent":"EU","capital":"Andorra la Vella","
    

    I got it working by changing the resource params (isArray: false)

    var resource = $resource('http://api.geonames.org/countryInfoJSON?username=okproject', {}, { 'query': { method: 'GET',isArray: false}});
    

    By the way I changed as well the username to "okproject" the default account for the rest call was failing as well.

    Snapshot of the result:

    enter image description here

    In your controller you will have to update the GetEvent callback

    $scope.callWithResource=function() {
        GeoService.getEvent().then(function (response) {            
            $scope.countries = response.geonames;
        });
    };