Sending HTTP GET and PUT Requests with the $http Service

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:

Image delete(url, [config])

Image get(url, [config])

Image head(url, [config])

Image jsonp(url, [config])

Image post(url, data, [config])

Image 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'});

Image

Table 25.2 Properties that can be defined in the config parameter for $http service requests

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:

Image data: Response data.

Image status: Response status.

Image header: Response header.

Image 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.

Listing 25.1 node_server.js: Implementing an Express server that supports GET and POST routes for an AngularJS controller


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);


Listing 25.2 service_http.js: Implementing an AngularJS controller that interacts with the webserver using the $http service


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   }]);


Listing 25.3 service_http.html: An AngularJS template that implements directives that are linked to webserver data


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>


Image

Figure 25.1 Implementing the $http service to allow AngularJS controllers to interact with the webserver.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.253.62