Chapter 3
Calls to the $http service methods return promises with two additional
methods (success and error) for easy callback registration.
Since the $http service returns promises from its methods' calls we can enjoy the full
power of the Promise API while interacting with a back-end. We can easily aggregate
callbacks, chain and join requests as well as take advantage of sophisticated error
handling in the asynchronous world.
Communicating with RESTful endpoints
The Representational State Transfer (REST) is a popular architectural choice for
exposing services over a network. The interface provided by $http allows us to
easily interact with RESTful endpoints from any AngularJS-based web application.
But AngularJS goes one step further, and provides a dedicated $resource service to
make interactions with RESTful endpoints even easier.
The $resource service
RESTful endpoints often expose CRUD operations that are accessible by calling
different HTTP methods on a set of similar URLs. The code that interacts witch such
endpoints is usually straightforward but tedious to write. The $resource service
allows us to eliminate the repetitive code. We can also start to operate on a higher
abstraction level and think of data manipulation in terms of objects (resources) and
method calls instead of low-level HTTP calls.
The $resource service is distributed in a separate file (angular-
resource.js), and resides in a dedicated module (ngResource).
To take advantage of the $resource service we need to include
the angular-resource.js file and declare dependency on the
ngResource module from our application's module.
To see how easy is to interact with the RESTful endpoint using the $resource
service we are going to construct an abstraction over the collection of users exposed
as a RESTfulservice by the MongoLab:
angular.module('resource', ['ngResource'])
.factory('Users', function ($resource) {
return
$resource('https://api.mongolab.com/api/1/databases/ascrum/
collections/users/:id', {