Reputation: 595
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
Upvotes: 0
Views: 1494
Reputation: 1758
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});
Upvotes: 1