Monday, October 8, 2012

AngularJS $resource Service

AngularJS provides the $resources service to provide an easy way to access REST resources.

Creating services can be as simple as follows:

angular.module('myResourceService', [ 'ngResource' ])
.factory(
'Cat',
function($resource) {
return $resource('/ws/cat/:catId',
{}, {
// resource with no custom method
});
})
.factory(
'Dog',
function($resource) {
return $resource('/ws/user/:dog/dogId',
{}, {
update: {method: 'PUT'} // custom method
});
});


Once they have been created, getting something from the web service is as simple as e.g.

Cat.get({catId:’xxxxx’},function(data) { // callback function contents });


By default, the following methods are implicitly declared for each resource:

{ 'get':    {method:'GET'},
 'save':   {method:'POST'},
 'query':  {method:'GET', isArray:true},
 'remove': {method:'DELETE'},
 'delete': {method:'DELETE'}
};


Notice that PUT is not supported, which is why it has to be added as a custom method (see example on top).

References:

No comments:

Post a Comment