AngularJS : AJAX and REST


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).

1
2
3
4
5
6
7
8
9
10
$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
    // this callback will be called asynchronously
    // when the response is available
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with status
    // code outside of the <200, 400) range
  });

To simplify the writing, the API provides the following methods: $http.get(config)$http.post(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:

1
2
3
4
5
{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

Then :

1
2
3
4
5
6
7
8
9
var Friend = $resource(url);
// create an instance
var friend = new Friend();
// or query to retrieve an instance
Friend.get({'id': id}, function(data) {
  friend = data;
});
// save object to server
friend.$save();

Class methods or object can be called 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])

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

1
$scope.Friend = $resource('/api/friends' + '/:id', {id: '@_id'}, {'update': {method: 'PUT' }});

The example below reuse the previous example by using $resource instead of $http, the updatemethod 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.

 Copy from http://www.itaware.eu/2012/10/15/angularjs-ajax-and-rest/
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s