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.
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 ...
No credit card required