The $http
service enables you to directly interact with the webserver 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])
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 25.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 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 25.1 through 25.3 implements an end-to-end AngularJS/Node.js web application that allows a user to initialize a list of days and remove days from the list. 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 25.1 implements the Node.js webserver that handles the GET
route /reset/days
and the POST
route /remove/day
. If there are fewer than two days in the list, the /remove/day
route returns an HTTP error.
Listing 25.2 implements the AngularJS application and controller. Notice that the removeDay()
method calls the /remove/day POST
route on the server and places the results in the scope variable $scope.days
. If an error occurs, the $scope.status
variable is set to the msg
value in the error response object. The resetDays()
method calls the /reset/days GET
route on the server and updates $scope.days
with the successful response.
Listing 25.3 implements an AngularJS template that includes the Initialize Days
button, status
message on error, and a list of days
. Figure 25.1 shows how the days are deleted and an error message is shown when too many days are removed.
01 var express = require('express'),
02 var bodyParser = require('body-parser'),
03 var app = express();
04 app.use('/', express.static('./static')).
05 use('/images', express.static( '../images')).
06 use('/lib', express.static( '../lib'));
07 app.use(bodyParser());
08 var days=['Monday', 'Tuesday', 'Wednesday',
09 'Thursday', 'Friday'];
10 var serviceDays = days.slice(0);
11 app.get('/reset/days', function(req, res){
12 serviceDays = days.slice(0);
13 res.json(serviceDays);
14 });
15 app.post('/remove/day', function(req, res){
16 if (serviceDays.length > 2){
17 serviceDays.splice(serviceDays.indexOf(req.body.day), 1);
18 console.log(days);
19 res.json(serviceDays);
20 }else {
21 res.json(400, {msg:'You must leave 2 days'});
22 }
23 });
24 app.listen(80);
01 angular.module('myApp', []).
02 controller('myController', ['$scope', '$http',
03 function($scope, $http) {
04 $scope.days=[];
05 $scope.status = "";
06 $scope.removeDay = function(deleteDay){
07 $http.post('/remove/day', {day:deleteDay}).
08 success(function(data, status, headers, config) {
09 $scope.days = data;
10 }).
11 error(function(data, status, headers, config) {
12 $scope.status = data.msg;
13 });
14 };
15 $scope.resetDays = function(){
16 $scope.status = "";
17 $http.get('/reset/days')
18 .success(function(data, status, headers, config) {
19 $scope.days = data;
20 }).
21 error(function(data, status, headers, config) {
22 $scope.status = data;
23 });
24 };
25 }]);
01 <!doctype html>
02 <html ng-app="myApp">
03 <head>
04 <title>AngularJS $http Service</title>
05 <style>span{color:red;}</style>
06 </head>
07 <body>
08 <div ng-controller="myController">
09 <h2>$http Service</h2>
10 <input type="button" ng-click="resetDays()"
11 value="Initialize Days"/>
12 {{status}}
13 <h3>Days Available</h3>
14 <div ng-repeat="day in days">
15 {{day}}
16 [<span ng-click="removeDay(day)">remove</span>]
17 </div>
18 </div>
19 <script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
20 <script src="/js/service_http.js"></script>
21 </body>
22 </html>