Reputation: 535
Here is my factory method:
.factory('lettersFactory', ['$resource', function ($resource) {
var url = "";
if(ionic.Platform.isAndroid()){
url = "/android_asset/www/";
}
return $resource(url + 'data/letters.json');
}])
And here is the controller:
.controller('LettersCtrl', ['$scope','lettersFactory', '$stateParams', '$state', '$ionicPopover', function($scope, lettersFactory, $stateParams, $state, $ionicPopover) {
$scope.letters = lettersFactory.query();
$scope.letter = lettersFactory.get({number:parseInt($stateParams.letterId, 10)});
}])
And here is the Error message:
Error in resource configuration for action
object
. Expected response to contain an array but got an GET (Request: data/letters.json {4})
And my letter.json is an array like this:
[
{"number":1,
"title": "title",
"content": "content"},
{"number":1,
"title": "title",
"content": "content"}
]
Thanks
Upvotes: 0
Views: 1503
Reputation: 48968
The default method set for $resource
contains these actions1:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
In your case the get
method is failing because the data from the XHR is an array and the method expects an object.
The query
method succeeds because the data from the XHR is an array and the method expects an array.
Use the get
method for object data; use the query
method for array data.
Update
how do you think I can use the query method in this situation to get a particular object from the array data?
One approach is to use the $promise
property of the returned resource object:
$scope.array = lettersFactory.query();
$scope.array.$promise.then(function(resourceArray) {
$scope.item = resourceArray[0];
});
It is important to realize that invoking a $resource
object method immediately returns an empty reference (object or array depending on isArray
). Once the data is returned from the server the existing reference is populated with the actual data.
The Resource instances and collections have additional properties:
$promise
: the promise of the original server interaction that created this instance or collection.
On success, the promise is resolved with the same resource instance or collection object, updated with data from server.
On failure, the promise is rejected with the http response object, without the resource property.
For more information, see AngularJS $resource API Reference
Upvotes: 0
Reputation: 2058
If the response should not be an array then you need set the isArray as false in query property.
'query': {method: 'GET', isArray: false }
Refer to the document.https://docs.angularjs.org/api/ngResource/service/$resource
Or you can pass the json as array from the controller.
Upvotes: 1