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 ...
Get AngularJS now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.