Chapter 3
For example, the MongoLab REST API is using the HTTP POST method to create
new items but the PUT method must be used to update existing entries. Let's
see how to define a custom update method (both the class-level update and the
instance-level $update):
.factory('Users', function ($resource) {
return $resource('https://api.mongolab.com/api/1/databases/ascrum/
collections/users/:id', {
apiKey:'4fb51e55e4b02e56a67b0b66',
id:'@_id.$oid'
}, {
update: {method:'PUT'}
});
})
As you can see defining a new method is as simple as supplying a third parameter
to the $resource factory function. The parameter must be an object of the
following form:
action: {method:?, params:?, isArray:?, headers:?}
The action key is a new method name to be generated. A generated method will
issue a HTTP request specified by method, params are holding default parameters
specific to this particular action and the isArray specifies, if data returned from
a back-end represent a collection (an array) or a single object. It is also possible to
specify custom HTTP headers.
The $resource service can only work with JavaScript arrays and objects as data
received from a back-end. Single values (primitive types) are not supported.
Methods returning a collection (ones flagged with isArray) must return a JavaScript
array. Arrays wrapped inside a JavaScript object won't be processed as expected.
Adding behavior to resource objects
The $resource factory is generating constructor functions that can be used as
any other JavaScript constructor to create new resource instances using the new
keyword. But we can also extend prototype of this constructor to add new behavior
to resource objects. Let's say that we want to have a new method on the user level
outputting a full name based on a first and last name. Here is the recommended
way of achieving this:
.factory('Users', function ($resource) {
var Users = $resource('https://api.mongolab.com/api/1/databases/
ascrum/collections/users/:id', {
apiKey:'4fb51e55e4b02e56a67b0b66',
id:'@_id.$oid'