$Resource – A Time to REST

The AngularJS $resource module is a factory which creates a resource that lets you interact with RESTful server-side data sources. Basically, you configure where you’re going and what it expects and AngularJS handles everything else.

The resource “class” object has methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

Action Verb
get GET
save POST
query GET
delete DELETE

Easily get your list by invoking the .query function

var User = $resource('/api/user', null);
var users = User.query();

What about PUT support? By default the .save will PUT your updates to the data source, but it can be easily implemented for clarity by creating a custom function.

var app = angular.module('app'. ['ngResource']);

app.factory('User',['$resource', function ($resource) {
    return $resource('/api/user/:id', null,
        {
            'update': { method:'PUT' }
        });
});

Now from your controller you simply need to call the User factory’s new update method.

User.update({id: userId}, user);

This is nice; but, what’s really cool is how AngularJS handles the return value. Unlike a Deferred / Promise value, the $resource module returns Array and Object references. At first, these objects are empty. But, when the server returns with data, AngularJS subsequently “hydrates” these empty objects with the deserialized data. This allows the $resource response to be injected into the Controller’s $scope before the server has responded.

Example User application

var app = angular.module('app' ['ngResource']);

app.factory('User',['$resource', function ($resource) {
    return $resource('/api/user/:id', null,
        {
            'update': { method:'PUT' }
        });
});


// We can retrieve a collection from the server
var users = User.query();

// create a new user
var newUser = new User();
newUser.Name = "Harry Reid";
newUser.$save();

// get a user from the server
var user = User.get({id: 1});
// update the user
user.Name = "John Smith";
user.update();

// delete a user
User.remove({id: 1});


Posted in AngularJS Tagged with: