Understanding angularJS $resource isArray property - angularjs

i'm learning angular's $resource service and in the angular tutorial a custom action is added (query) that has its method set to 'get' and isArray is set to true
return $resource('phones/:phoneId.json', {}, {
query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
});
However, if you look at the docs for $resource the 'query' action already has its method set to 'get' and isArray is already set to true by default. So i thought that i can just leave those properties out.
This works for the method property, but it turns out that if i leave out the isArray property i get this error:
Error: [$resource:badcfg] Error in resource configuration for action
query. Expected response to contain an object but got an array
Why is that?

I think you have misunderstood the documentation.
By default without adding any custom actions, the following are supported:
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
So by default the query action expects an array to be returned which makes sense since a query generally would return an array of items.
So if you use:
phonecatServices.factory('Phone', ['$resource', function($resource){
return $resource('phones/phones.json');
}]);
You can then perform a query like so:
var queryParams = { name: 'test' };
Phone.query(queryParams, {}, function (response) {
$scope.phones = response;
});
Now if you wanted to add a custom action then the default for isArray is false so:
return $resource('phones/:phoneId.json', {}, {
someCustomAction: {method:'GET', params:{phoneId:'phones'} }
});
would need to return an object. If an array was returned then isArray would need to be set to true like so:
return $resource('phones/:phoneId.json', {}, {
someCustomAction: {method:'GET', params:{phoneId:'phones'}, isArray: true }
});

Related

How do I call $resource service from controller in angularJs

This is get service function where I am calling the API
.factory('Report', function($resource, API_URL) {
return $resource(API_URL +
'security/:userId/1498780800000/listOfDeliveries', {
userId : '#userId',
expected : '#expected',
arg1 : '#arg1'
}, {
update: {
method: 'PUT'
}
});
})
In the app.js I have this below controller
.controller('ReportsController', function($scope, $rootScope,
ProfileData, $state, $timeout, Report) {
})
First of all, you need to check how angular factory & service work.
Your factory return a $resource, so read the doc about $resource
A resource "class" object with methods for the default set of resource
actions optionally extended with custom actions. The default set
contains these actions:
{
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
So, you can use theses methods: Report.get(), Report.save(), Report.query(), Report.remove(), Report.delete()
In addition there are custom method you defined: Report.update()
And you can pass userId as params so:
Report.get({userId: 1234}); will call a GET request to: API_URL+'security/1234/1498780800000/listOfDeliveries
(expected and args1 are not in url so I dont think you need them)
What's returning Report.get() ?
Class actions return empty instance (with additional properties below). Instance actions return promise of the action
So Report.get(...) is returning a promise, you will get data by:
Report.get(...).then(function(data) {
$scope.requestData = data;
});

Angular-resource query error

I'm receiving the following error from $resource:
Error: [$resource:badcfg] Error in resource configuration for action `query`. Expected response to contain an array but got an object
the API is not returning an Array but it return this:
{
list: [...items...],
next: true,
limit: 100,
last: 0
}
I need to get the entire object with query() and push list in my $scope.items.
The other params needs for pagination or infinite scroll.
How can I do that?
EDIT:
This is my factory:
angular.module('app').factory('Items', ['$resource',
function ($resource) {
return $resource('/items/:id', { id: '#id' }, {
'query': {
method: 'GET',
isArray: false
},
update: {
method: 'PUT'
}
});
}
]);
Your factory is right, just remove single quotes from query:
...
query: {
method: 'GET',
isArray: false
}
...
EDIT after below comment
I had exactly the same problem few days ago, which was solved by setting isArray to true. So I quite confident in syntax, but for me I have slightly different declaration of factory:
angular.module('docAccessApp',[]).factory('Access',function($resource){
return $resource('http://localhost:8080/documentAccesses/:id',{id:'#_id'},{
query: {
method: 'GET',
isArray:false
}
});
});
Maybe you need to Hard Reload the page so that browser refreshes all the js cache.

How to retrieve objects from rest url with multiple parameters using angular

How can i create a factory that can retrieve data from
/rest/company/:companyid/employee/:id
when i use this url in the factory I get an error: Unknown provider companyidProvider
Thank you,
Kyle
Service:
app.factory('EmployeeByCompany', function ($resource,companyid) {
return $resource('app/rest/company/:companyid/employee/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': { method: 'GET'}
});
});
I'm guessing the error is from having the companyid as a parameter with $resource. What is the right way for a service to call this url?
If you are learning or geting started, try Restangular https://github.com/mgonto/restangular

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

How fix Error:
[$resource:badcfg] Error in resource configuration. Expected response
to contain an array but got an object?
// Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource('../rest/api.php?method=getTask&q=*',{ 'get': {method:'GET'}});
})
// Controller
$scope.getTask = getTaskService.query(function (response) {
angular.forEach(response, function (item) {
if (item.numFound > 0) {
for(var i = 0; i < item.numFound; i++) {
$scope.getTasks[i] = item.docs[i];
}
}
});
});
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
$resource("../rest/api"}).get();
returns an object.
$resource("../rest/api").query();
returns an array.
You must use :
return $resource('../rest/api.php?method=getTask&q=*').query();
First of all you should configure $resource in different manner: without query params in the URL. Default query parameters may be passed as properties of the second parameter in resource(url, paramDefaults, actions). It is also to be mentioned that you configure get method of resource and using query instead.
Service
angular.module('admin.services', ['ngResource'])
// GET TASK LIST ACTIVITY
.factory('getTaskService', function($resource) {
return $resource(
'../rest/api.php',
{ method: 'getTask', q: '*' }, // Query parameters
{'query': { method: 'GET' }}
);
})
Documentation
http://docs.angularjs.org/api/ngResource.$resource
In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
User $resource("apiUrl").query();
Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.
To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.
For anyone coming here in 2021, another way this request may look is as follows (at least it was in our app)
angular.module('load').factory('StateService', ['$resource', 'store', function($resource, store) {
return $resource('/some/url', {}, {
fetchAllStateCodes: {
method: 'GET',
isArray: true, // Response is an array of objects
headers: {
"Authorization": "Bearer " + store.get("jwt"),
"Content-type": "application/json"
}
}
});
}]);
From all of the good answers, it still wasn't obvious to me as to where to put the isArray flag...

Angularjs: How to use $resource to serve an array of objects

I had a $resource that servers two files, names.js and birthday.js:
// names.js
{
name: John,
name: Mary,
}
// birthday.js
{
John: 28,
Mary: 28
}
It works great in my controller. But I couldn't run ng-repeat on it. So I converted the data to a format that was used in the ng-repeat docs:
// friends.js
friends = [{name:'John', age:25}, {name:'Mary', age:28}];
But now my provider for friends.js returns an array of characters (not very useful) or an object of characters. How can I make it so that my provider returns a useful format of the data?
The query in the service is:
friends: $resource('data/friends.js', {}, {
query: {method: 'GET', params: {}, isArray: true[or false]}
})
In short, how do you use a $resource to provide friends.js?
How do you query your $resource?
The get method is expecting an object while the query method is expecting an array.
This is the default methods available on a $resource :
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
More info available here :
AngularJS resource documentation

Resources