0

I'm using a $resource in Angular, and have set up the resource like this:

angular.module('MyApp')
.factory('Appointment', function($resource){
    return $resource('/api/admin/:id', { id: "@_id" }, {
         query: {method:'GET', isArray:true}
    });
})

Now, when I use this resource in one controller (adminController) it works ok:

angular.module('MyApp')
.controller('adminController', ['$scope', 'Appointment', '$state', '$rootScope' , '$stateParams', '$log', '$modal','uiGmapGoogleMapApi',  function($scope, Appointment, $state, $rootScope, $stateParams, $log, $modal, uiGmapGoogleMapApi) {
$scope.apps  = Appointment.query();

}])

but when I try to use it in another one (DetailCtrl) i get the above error:

angular.module('MyApp')
.controller('DetailCtrl', ['$scope', 'Appointment', '$state', '$rootScope' , '$stateParams', '$log', '$modal', 'uiGmapGoogleMapApi', function($scope, Appointment, $state, $rootScope, $stateParams, $log, $modal, uiGmapGoogleMapApi) {

$scope.detail = Appointment.query({id: $stateParams.id})

}])

can anyone explain what it going on? I'm getting this error:

Error: [$resource:badcfg] Error in resource configuration for action `query`. Expected response to contain an array but got an object
2

1 Answer 1

1

When you are calling it the first time, you are not passing in an id parameter, so you end up actually calling the URL /api/admin/, which apparently returns an array.

The second call in DetailCtrl is passing an id, so it is calling a different URL, say /api/admin/12, and this service is returning a single object, so you get the error you describe.

You need different $resources for the different expected return values - the same call will not be able to return both an array and a single object.

In my own code, I would split it up something like:

angular.module('MyApp')
.factory('Appointment', function ($resource) {

    return {

        list: $resource('/api/admin', {}, {
            query: { method: 'GET', isArray: true }
        })

        single: $resource('/api/admin/:id', {}, {
            query: { method: 'GET', isArray: false }
        })

    };

});

And you could fetch a list with

$scope.apps = Appointment.list.query();

and a single appointment with

$scope.detail = Appointment.single.query({id: $stateParams.id});

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for this - i'm basically an idiot - i should be calling Appointment.get - not Appointment.query for a single object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.