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:
var
xmlhttp
=
new
XMLHttpRequest
();
xmlhttp
.
onreadystatechange
=
function
()
{
if
(
xmlhttp
.
readystate
==
4
&&
xmlhttp
.
status
==
200
)
{
var
response
=
xmlhttp
.
responseText
;
}
else
if
(
xmlhttp
.
status
==
400
)
{
// or really anything in the 4 series
// Handle error gracefully
}
};
// Set up connection
xmlhttp
.
open
(
"GET"
,
"http://myserver/api"
,
true
);
// Make the request
xmlhttp
.
send
();
This is a lot of work for such a simple, common, and often repeated task. More often than not, we ...
Get AngularJS: Up and Running 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.