I'm creating a resource to pass data into my controller for an existing api that need to hook into. I am not able to modify the back end unfortunately.
My Resource factory currently looks like this:
'use strict';
angular.module('XXX')
.factory('elements', function (
$resource
) {
return $resource('http://XXX/api/v1/elements/:id',
{
callback: 'JSON_CALLBACK',
id: '@id'
},
{
query: {
method: 'JSONP',
params: {
id: '@id'
}
},
all: {
method: 'JSONP',
params: {}
}
}
);
});
The elements.query() works fine, however the elements.all() does not work unfortunately. I did notice that in the returned content in my network tab, begins with angular.callbacks._2([{... DATA...}]) - this doesn't seem right to me.
UPDATE.....
OK so i've got it working with this:
angular.module('XXX')
.factory('element', function (
$resource
) {
return $resource('http://XXX/api/v1/elements/:id',
{
id: '@id',
callback : 'JSON_CALLBACK',
},
{
query: {
method: 'JSONP',
params: {
id: '@id'
}
},
all: {
method: 'JSONP',
isArray: true,
params: {
callback : 'JSON_CALLBACK',
}
}
}
);
});
however the json that it returns to the console comes in as an array.. I am able to parse it for use, but just wondering now if this is best practice?
That is the way isArray is meant for. You need the isArray flag, because angular has to create an empty Object - in this case an Array - before the request is sent. So all bindings will work, because you have the same reference. At the time the result has arrived, it will be populated to your variable, the result object / array.
We are doing the service calls like this, maybe it will help you:
.factory('Person', function($resource, AppConfig) {
var Person = $resource(AppConfig.remoteURL + '/person/:id', {}, {
query: {method:'GET'},
queryAll: {method:'GET', isArray: true},
create: {method:'POST'},
update: {method: 'PUT'}});
return Person;
});
and call it like this:
Person.queryAll(function (result) {
angular.isArray(result); // should be true
}, function (error)
{
//doh!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With