AngularJS : AJAX and REST

This entry was posted by on Lundi, 15 octobre, 2012 at

Although with AngularJS you can develop applications without access to the server, you will be quickly limited when it is necessary to store information. Communication with a server is essential and AngularJS provides two services for this:

Moreover, to facilitate testing there’s 2 $httpBackend objects (one for unit tests, one for functional tests) to simulate server’s behavior.

To demonstrate the use of these two services we will use the previous example. The friends list will now be stored on the server side and the server will allow requests to retrieve one or more items from the list, modify, delete and create new ones (CRUD).
We will simulate the access servers using $httpBackend and methods when*.

$http with AJAX

The service $http uses the deferred / promise API through the $q service. $http(config) is a function taking a dictionary of parameters for parameter and returns an object promised that implements two functions success(data) and error(msg).

To simplify the writing, the API provides the following methods: $http.get(config), $, data), $http.head(config), $http.put(config, data), $http.delete(config), $http.jsonp(config).

There is also a feature of memory cache for storing the response.

But documentation is quite clear it is not necessary to say more.

The example below take the tour of the different methods calls and illustrate clearly the use of $http. You will find in app.js routes declaration and server simulation behavior via the $httpBackend object and in controllers.js request calls via $http:

Note the use of $http.jsonp(config) which differs because you need to add JSON_CALLBACK in URL parameters.
As the interceptor response which will be discussed in a future article on authentication.

REST $resource

Unlike $http, $resource provided explicit methods to call the server.
$resource(url [, paramDefaults], [actions]) is a function that returns a class that contains the following methods:

Then :

Class methods or object can be called with the following parameters:

Methods can be extended to create its own calls and make the code more explicit, it is the case in the example with the addition of the method update

The example below reuse the previous example by using $resource instead of $http, the update method is used to update the name of a friend:

Note that $resource is declared in a separate module of the based modules, i.e. we need to add the js file (see index.html) and declare the ngResource dependency in your module (see controllers.js).

The use of these services is really simple, the two examples show it and allow an overview of different methods calls.

Comments are closed.