Ways to Communicate with REST Services
Categories: Angular Angular JS
Ways to Communicate with REST Services
There are currently two ways to communicate with REST services using AngularJS:
The $http service
This service provides low-level interaction with REST services using the browser’s
XMLHttpRequest object.
The $resource object
This object provides a high-level approach to interacting with REST services, simplifying the process considerably.
We will focus mostly on using the $resource object for communicating with REST services and leave the $http service discussion to other books (although we will use the $http service in later chapters for handling Basic Authentication headers). All our project code uses the $resource object.
The following code shows how to define an AngularJS service that can be used to interact with the BlogPost REST service. Notice that we pass the REST service URL to the $resource object. The methods defined match the REST services that are defined on that particular URL. Once the BlogPost service is defined, it can be used like a standard JavaScript object to access the different REST services defined on this URL:
/* chapter6/services.js */
'use strict';
/* Services */
var blogServices =
angular.module('blogServices', ['ngResource']);
blogServices.factory('BlogPost', ['$resource',
function($resource) {
return $resource("http://www.micbutton.com/rs/blogPost", {}, {
get: {method: 'GET', cache: false, isArray: false},
save: {method: 'POST', cache: false, isArray: false},
update: {method: 'PUT', cache: false, isArray: false},
delete: {method: 'DELETE', cache: false, isArray: false}
});
}]);
Using the $resource object is by far the easiest way to call REST services. As you can see from this example, the AngularJS service code is straightforward and really fairly uncomplicated. Even when many services are defined, the services.js file is relatively simple.
The AngularJS $http service mentioned earlier is another way to call REST services. However, using the $http service would require many more lines of code related to REST service calls than we need using the $resource object. We do use the $http service in several places in the blog application, though, such as to send a Basic Authentication header to REST services.