Chapter 6. Server Communication Using $http
In Chapter 5, we looked at AngularJS services and how they differ from controllers. We also explored some basic core AngularJS built-in services, and saw how to create our own AngularJS service as well.
In this chapter, we explore how to start creating applications that can communicate with a server to fetch and store data. In particular, we will work with the $http service and save and update information. By the end of the chapter, we as developers should be extremely comfortable working with asynchronous tasks in AngularJS and with server communication, because we have built the infrastructure we might need for a full-fledged application.
Fetching Data with $http Using GET
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:
varxmlhttp=newXMLHttpRequest();xmlhttp.onreadystatechange=function(){if(xmlhttp.readystate==4&&xmlhttp.status==200){varresponse=xmlhttp.responseText;}elseif(xmlhttp.status==400){// or really anything in the 4 series// Handle error gracefully}};// Set up connectionxmlhttp.open("GET","http://myserver/api",true);// Make the requestxmlhttp.send();
This is a lot of work for such a simple, common, and often repeated task. More often than not, we ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access