Angular JS RESTful Services

ngResource

 

This a factory which creates a resource object that lets you build CRUD operations with RESTful server-side data sources. Using this client we can make requests to the server for data in an easier way, without having to deal with the lower-level $http API, HTTP methods and URLs.

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

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

Calling these methods invoke an $http with the specified http method, destination and parameters. When the data is returned from the server then the object is an instance of the resource class. The actions save, remove and delete are available on it as methods with the $ prefix. This allows you to easily perform CRUD operations (create, read, update, delete) on server-side data like this:

var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
  user.abc = true;
  user.$save();
});

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

The action methods on the class object or instance object can be invoked with the following parameters:

  • HTTP GET “class” actions: Resource.action([parameters], [success], [error])
  • non-GET “class” actions: Resource.action([parameters], postData, [success], [error])
  • non-GET instance actions: instance.$action([parameters], [success], [error])

Success callback is called with (value, responseHeaders) arguments, where the value is the populated resource instance or collection object. The error callback is called with (httpResponse) argument.

Class actions return empty instance (with additional properties below). Instance actions return promise of the action.

The Resource instances and collections have these additional properties:

  • $promise: the promise of the original server interaction that created this instance or collection.On success, the promise is resolved with the same resource instance or collection object, updated with data from server. This makes it easy to use in resolve section of $routeProvider.when() to defer view rendering until the resource(s) are loaded.On failure, the promise is resolved with the http response object, without the resource property.If an interceptor object was provided, the promise will instead be resolved with the value returned by the interceptor.
  • $resolved: true after first server interaction is completed (either with success or rejection), false before that. Knowing if the Resource has been resolved is useful in data-binding.The Resource instances and collections have these additional methods:
  • $cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.

Getting Started

  1. Update Bower dependencies in bower.json configuration file. Install new dependency "angular-resource": "1.4.x" by running:npm install.Or you can download angular-resource.js and include it in your HTML page. The script can be downloaded from http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular-resource.min.js.
  2. In your main app module, app/js/app.js declare a dependency on the Service factory appService module.
    var app = angular.module('mainApp',['myApp.services', 'myApp.controllers']); //mainApp is our main module

     

  3. Create the RESTful API endpoints in your backend application i.e Spring MVC controllers or Node + Express + MongoDB.$resource expects a classic RESTful backend. This means you should have REST endpoints in the following format:REST Endpoints
  4. Create Services factory module. Declare a dependency on the ngResource module in order to use $resource. The next step is calling the $resource() function with your REST endpoint. This function call returns a $resource class representation which can be used to interact with the REST backend.app/js/services.js.
    var appService = angular.module('myApp.services', ['ngResource'])
    
    appService.factory('Entry', ['$resource', function($resource) {
      return $resource('/api/entries/:id'); // Note the full endpoint address
    }]);

    The result of the function call is a resource class object which has the following five methods by default:

    1. get()
    2. query()
    3. save()
    4. remove()
    5. delete()
  5. Create controller to use the get(), query() and save() methods. app/js/controllers.js:
    var = appController = angular.module('myApp.controllers',[]);
    
    appController.controller('ResourceController',function($scope, Entry) {
      var entry = Entry.get({ id: $scope.id }, function() {
        console.log(entry);
      }); // get() returns a single entry
    
      var entries = Entry.query(function() {
        console.log(entries);
      }); //query() returns all the entries
    
      $scope.entry = new Entry(); //You can instantiate resource class
    
      $scope.entry.data = 'some data';
    
      Entry.save($scope.entry, function() {
        //data saved. do something here.
      }); //saves an entry. Assuming $scope.entry is the Entry object  
    });
    • The get() function in the above snippet issues a GET request to /api/entries/:id. The parameter :id in the URL is replaced with $scope.id.The second argument to get() is a callback which is executed when the data arrives from server. This is a useful trick because you can set the empty object returned by get() to the $scope and refer to it in the view.
    • The save() function issues a POST request to /api/entries with the first argument as the post body. The second argument is a callback which is called when the data is saved. You might recall that the return value of the $resource() function is a resource class. So, in our case we can call new Entry() to instantiate an actual object out of this class, set various properties on it and finally save the object to backend.
    • Ideally, you will only use get() and query() on the resource class (Entry in our case).
  6. All the non GET methods like save() and delete()are prefixed with a $. So, the methods available in the $resource instance (as opposed to $resource class) are:
    1. $save()
    2. $delete()
    3. $remove()

    For instance, the method $save() is used as following:

    $scope.entry = new Entry(); //this object now has a $save() method
    $scope.entry.$save(function() {
      //data saved. $scope.entry is sent as the post body.
    });

     

  7. For update operation we need to modify our custom factory Entity as shown below. app/js/services.js:
    myApp.services.factory('Entry', function($resource) {
      return $resource('/api/entries/:id', { id: '@_id' }, {
        update: {
          method: 'PUT' // this method issues a PUT request
        }
      });
    });

    The second argument to $resource() is a hash indicating what should be the value of the parameter :id in the URL. Setting it to @_id means whenever we will call methods like $update() and $delete() on the resource instance, the value of :id will be set to the _id property of the instance. This is useful for PUT and DELETE requests. Also note the third argument. This is a hash that allows us to add any custom methods to the resource class.

    If the method issues a non-GET request it’s made available to the $resource instance with a $ prefix. So, let’s see how to use our $update method. Assuming we are in a controller, app/js/controllers.js:

    $scope.entry = Movie.get({ id: $scope.id }, function() {
      // $scope.entry is fetched from server and is an instance of Entry
      $scope.entry.data = 'something else';
      $scope.entry.$update(function() {
        //updated in the backend
      });
    });

    When the $update() function is called, it does the following:

    1. AngularJS knows that $update() function will trigger a PUT request to the URL /api/entries/:id.
    2. It reads the value of $scope.entry._id, assigns the value to :id and generates the URL.
    3. Sends a PUT request to the URL with $scope.entry as the post body.
  8. For delete operations, app/js/controllers.js:
    $scope.entry = Movie.get({ id: $scope.id }, function() {
      // $scope.entry is fetched from server and is an instance of Entry
      $scope.entry.data = 'something else';
      $scope.entry.$delete(function() {
        //gone forever!
      });
    });

     

  9. The $resource function also has an optional fourth parameter. This is a hash with custom settings. Currently, there is only one setting available which is stripTrailingSlashes. By default this is set to true, which means trailing slashes will be removed from the URL you pass to $resource(). If you want to turn this off you can do so like this:
    angular.module('myApp.services').factory('Entry', function($resource) {
      return $resource('/api/entries/:id', { id: '@_id' }, {
        update: {
          method: 'PUT' // this method issues a PUT request
        }
      }, {
        stripTrailingSlashes: false
      });
    });

     

 

Tutorials

 

 

References