why does $http service consume full url of rest service and $resource doesn't?

This is my service:

app.factory("ResourceService", function ($resource, $q, $http) {
return {
    getAll: function () {
        var deferred = $q.defer();
        $http.get('https://dog.ceo/api/breeds/list/all').then(function (response) {
            deferred.resolve(response);
        }, function (error) {
            deferred.reject(error);
        });
        return deferred.promise;
    },
    allUsingResource: function () {
        return $resource('https://dog.ceo/api/breeds/list/all');
    }
}
});

This is my controller:

app.controller("Controller", function ($scope, ResourceService) {
function getAll() {
    ResourceService.getAll().then(function (response) {
        $scope.all = response.data;
    }, function (error) {
        console.log(error);
    });
}
function runAll() {
    var data = ResourceService.allUsingResource();
    data.query(function (response) {
        console.log(response);
    }, function (error) {
        console.log(error);
    });
}
runAll();
getAll();
});

While everything goes swell with $http, i get badcfg with $resource:

Error: [$resource:badcfg] http://errors.angularjs.org/1.6.5/$resource/badcfg?p0=query&p1=array&p2=object&p3=GET&p4=https%3A%2F%2Fdog.ceo%2Fapi%2Fbreeds%2Flist%2Fall

What am I missing?

Upvotes: 1

Views: 49

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

When you run data.query on $resource object by default it expects array in response:

 'query':  {method:'GET', isArray:true},

So be sure you return an array and not an object from https://dog.ceo/api/breeds/list/all


Read error from URL Angularjs Provided for you:

https://docs.angularjs.org/error/$resource/badcfg?p0=query&p1=array&p2=object&p3=GET&p4=https:%2F%2Fdog.ceo%2Fapi%2Fbreeds%2Flist%2Fall

Error in resource configuration for action query. Expected response to contain an array but got an object (Request: GET https://dog.ceo/api/breeds/list/all)

Description

This error occurs when the $resource service expects a response that can be deserialized as an array but receives an object, or vice versa. By default, all resource actions expect objects, except query which expects arrays.

To resolve this error, make sure your $resource configuration matches the actual format of the data returned from the server.

For more information, see the $resource API reference documentation.

Upvotes: 0

Related Questions