The $http
service enables you to directly interact with the web server from your AngularJS code. The $http
service uses the browser’s XMLHttpRequest
object underneath, but from the context of the AngularJS framework.
There are two ways to use the $http
service. The simplest is to use one of the following built-in shortcut methods that correspond to standard HTTP requests:
■ delete(
url, [
config])
■ get(
url, [
config])
■ head(
url, [
config])
■ jsonp(
url, [
config])
■ post(
url,
data, [
config])
■ put(
url,
data, [
config])
■ patch(
url,
data, [
config])
In these methods, the url
parameter is the URL of the web request. The optional config
parameter is a JavaScript object that specifies the options to use when implementing the request. Table 9.2 lists the properties you can set in the config
parameter.
You can also specify the request, URL, and data by sending the config
parameter directly to the $http(
config)
method. For example, the following two lines are exactly the same:
$http.get('/myUrl'),
$http({method: 'GET', url:'/myUrl'});
When you call a request method by using the $http
object, you get back an object with the promise methods success()
and error()
. You can pass to these methods a callback function that is called if the request is successful or if it fails. These methods accept the following parameters:
■ data: Response data.
■ status: Response status.
■ header: Response header.
■ config: Request configuration.
The following is a simple example of implementing the success()
and error()
methods on a get()
request:
$http({method: 'GET', url: '/myUrl'}).
success(function(data, status, headers, config) {
// handle success
}).
error(function(data, status, headers, config) {
// handle failure
});
The code in Listings 9.1 through 9.3 implements a simple Node.js web service and AngularJS application that accesses it. The web server contains a simple JavaScript object with items and count to mimic the stock of a store. The web application enables a user to tell the server to restock the store, and buy and use items. The example is very rudimentary so that the code is easy to follow, but it incorporates GET
and POST
requests as well as error-handling examples.
Listing 9.1 implements the Node.js web server that handles the GET
route /reset/data
and the POST
route /buy/item
. If the count of an item is zero, the /buy/item
route returns an HTTP error. The first few lines simply set up the Node.js server. Don’t worry if you don’t follow exactly what is happening there. The initStore()
function initializes the products and counts for items. On line 17 the GET
route /reset/data
is initialized and returns the store object as JSON. On line 21 the POST
rout is initialized. This route decrements the item count and returns the store data (typically it would not need to return the full data, but for this simple example it makes the code cleaner). If the item is out of stock, a 400 error is returned.
You will need to stop the normal server.js
HTTP server if it is running before starting service_server.js
from Listing 9.1. Also, you will want to place the service_server.js
file from Listing 9.1 in the parent folder to the service_http.html
in Listing 9.2 for the paths to match up properly in the Node.js static routes. The structure should look similar to this:
./service_server.js
./ch09/service_http.html
./ch09/js/service_http.js
01 var express = require('express'),
02 var bodyParser = require('body-parser'),
03 var app = express();
04 app.use('/', express.static('./'));
05 app.use(bodyParser.urlencoded({ extended: true }));
06 app.use(bodyParser.json());
07 function initStore(){
08 var items = ['eggs', 'toast', 'bacon', 'juice'];
09 var storeObj = {};
10 for (var itemIDX in items){
11 storeObj[items[itemIDX]] =
12 Math.floor(Math.random() * 5 + 1);
13 }
14 return storeObj;
15 }
16 var storeItems = initStore();
17 app.get('/reset/data', function(req, res){
18 storeItems = initStore();
19 res.json(storeItems);
20 });
21 app.post('/buy/item', function(req, res){
22 if (storeItems[req.body.item] > 0){
23 storeItems[req.body.item] =
24 storeItems[req.body.item] - 1;
25 res.json(storeItems);
26 }else {
27 res.json(400, { msg: 'Sorry ' + req.body.item +
28 ' is out of stock.' });
29 }
30 });
31 app.listen(80);
Listing 9.2 implements the AngularJS application and controller. Notice that the buyItem()
method calls the /buy/item POST
route on the server and places the results in the scope variable $scope.storeItems
. If an error occurs, the $scope.status
variable is set to the msg
value in the error response object. The resetStore()
method calls the /reset/data GET
route on the server and updates $scope.storeItems
with the successful response.
Listing 9.3 implements an AngularJS template that includes the Restock Store
button, status
message on error, and a list of store items. Figure 9.1 shows how the item counts get adjusted when items are bought and used, and the out-of-stock error message is shown when the user tries to buy an out-of-stock item.
01 angular.module('myApp', []).
02 controller('myController', ['$scope', '$http',
03 function($scope, $http) {
04 $scope.storeItems = {};
05 $scope.kitchenItems = {};
06 $scope.status = "";
07 $scope.resetStore = function(){
08 $scope.status = "";
09 $http.get('/reset/data')
10 .success(function(data, status, headers, config) {
11 $scope.storeItems = data;
12 })
13 .error(function(data, status, headers, config) {
14 $scope.status = data;
15 });
16 };
17 $scope.buyItem = function(buyItem){
18 $http.post('/buy/item', {item:buyItem})
19 .success(function(data, status, headers, config) {
20 $scope.storeItems = data;
21 if($scope.kitchenItems.hasOwnProperty(buyItem)){
22 $scope.kitchenItems[buyItem] += 1;
23 } else {
24 $scope.kitchenItems[buyItem] = 1;
25 }
26 $scope.status = "Purchased " + buyItem;
27 })
28 .error(function(data, status, headers, config) {
29 $scope.status = data.msg;
30 });
31 };
32 $scope.useItem = function(useItem){
33 if($scope.kitchenItems[useItem] > 0){
34 $scope.kitchenItems[useItem] -= 1;
35 }
36 };
37 }]);
01 <!doctype html>
02 <html ng-app="myApp">
03 <head>
04 <title>AngularJS $http Service</title>
05 <style>
06 span {
07 color:red; cursor: pointer; }
08 .myList {
09 display: inline-block; width: 200px;
10 vertical-align: top; }
11 </style>
12 </head>
13 <body>
14 <div ng-controller="myController">
15 <h2>GET and POST Using $http Service</h2>
16 <input type="button" ng-click="resetStore()"
17 value="Restock Store"/>
18 {{status}}
19 <hr>
20 <div class="myList">
21 <h3>The Store</h3>
22 <div ng-repeat="(item, count) in storeItems">
23 {{item}} ({{count}})
24 [<span ng-click="buyItem(item)">buy</span>]
25 </div>
26 </div>
27 <div class="myList">
28 <h3>My Kitchen</h3>
29 <div ng-repeat="(item, count) in kitchenItems">
30 {{item}} ({{count}})
31 [<span ng-click="useItem(item)">use</span>]
32 </div>
33 </div>
34 </div>
35 <script src="http://code.angularjs.org/1.3.0/angular.min.js"></script>
36 <script src="js/service_http.js"></script>
37 </body>
38 </html>