Mastering Web Application

(Rick Simeone) #1

Communicating with a Back-end Server


Instance level methods


The $resource service will not only generate a constructor function, but also will
add prototype (instance) level methods. The instance level methods are equivalents
of their class-level counterparts but operate of a single instance. For example, a user
can be deleted either by calling:


Users.delete({}, user);

Or by invoking a method on the user's instance like:


user.$delete();

Instance-level methods are very convenient, and allow us write concise code-
manipulating resources. Let's see another example of saving a new user:


var user = new Users({
name:'Superhero'
});
user.$save();

This could be re-written using the class-level save method:


var user = {
name:'Superhero'
};
Users.save(user);

The $resource factory generates both class-level and instance level
methods. The instance level-methods are prefixed with the $ character.
Both the methods have the equivalent functionality so it is up to you to
choose the more convenient form depending on your use-case.

Custom methods


By default the $resource factory generates a set of methods that is sufficient for
typical use-cases. If a back-end uses different HTTP verbs for certain operations
(For example, PUT or PATCH) it is relatively easy to add custom methods on a
resource level.


By default the $resource factory doesn't generate any method
corresponding to HTTP PUT requests. If your back-end maps
any operations to HTTP PUT requests you will have to add those
methods manually.
Free download pdf