O'Reilly logo

AngularJS by Brad Green, Shyam Seshadri

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Communicating with Servers

Up to this point, we have mostly seen how your AngularJS application should be laid out, how the different AngularJS pieces fit together and work, and a bit on how templating in AngularJS works. Together, this allows you to build some sleek, sexy apps, but they are restricted mostly to the client side. We saw a little bit of the server-side communication with the $http service back in Chapter 2, but in this chapter, we’ll dig a little bit deeper into how you would use it in a real-world application.

In this chapter, we will talk about how AngularJS allows you to communicate with your server, both at the lowest levels of abstraction and with the nice wrappers that it provides. Furthermore, we will go into how AngularJS can help you speed up your application with its built-in caching mechanism. If you want to develop a realtime application with AngularJS using SocketIO, there is an example in Chapter 8 of a possible way to wrap SocketIO as a directive and use it, so we won’t cover that here.

Communicating Over $http

The traditional way of making a request to the server from AJAX applications (using XMLHttpRequests) involves getting a handle on the XMLHttpRequest object, making the request, reading the response, checking the error codes, and finally processing the server response. It goes something like this:

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
 if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
   var response ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required