Mastering Web Application

(Rick Simeone) #1
Chapter 3

The second argument to the $resource function allows us to define default
parameters that should be sent with each request. Please note that here by
"parameters" we mean both placeholders in a URL template, and standard request
parameters sent as a query string. AngularJS will try first to "fill holes" in the URL
template, and then will add remaining parameters to the URL's query string.


The default parameters can be either static (specified in a factory) or dynamic, taken
from a resource object. Dynamic parameter values are prefixed with a @ character.


Constructor-level and instance-level methods

The $resource service automatically generates two sets of convenience methods.
One set of methods will be generated on the constructor-level (class-level) for a given
resource. The aim of those methods is to operate on collections of resources or cater
for the situation where we don't have any resource instance created. The other set of
methods will be available on an instance of a particular resource. Those instance-level
methods are responsible for interacting with one resource (one record in a data store).


Constructor-level methods


The constructor function generated by the $resource has a set of methods
corresponding to different HTTP verbs:



  • Users.query(params, successcb, errorcb): It issues an HTTP GET
    request and expects an array in the JSON response. It is used to retrieve
    a collection of items.

  • Users.get(params, successcb, errorcb): It issues an HTTP GET
    request and expects an object in the JSON response. It is used to retrieve
    a single item.

  • Users.save(params, payloadData, successcb, errorcb): It issues
    an HTTP POST request with request body generated from the payload.

  • Users.delete(params,successcb, errorcb) (and its alias: Users.
    remove): It issues an HTTP DELETE request.


For all the methods listed earlier the successcb and errorcb denote a success and
error callback functions, respectively. The params argument allows us to specify
per-action parameters that are going to end up either as part of the URL or as a
parameter in a query string. Lastly, the payloadData argument allows us to specify
the HTTP request body where appropriate (POST and PUT requests).

Free download pdf