Click here to Skip to main content
15,890,557 members
Articles / Programming Languages / Javascript
Tip/Trick

$http in Angular Simply Explained

Rate me:
Please Sign up or sign in to vote.
2.78/5 (3 votes)
18 Dec 2016CPOL2 min read 5.3K   3  
$http in Angular simply explained

Introduction

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise (https://docs.angularjs.org/api/ng/service/$http).

This article will illustrate a simple example using the $http service of AngularJS. The example will demonstrate checking the IP address invoking the URL, http://ip.jsontest.com/ which will return your IP address in JSON form.

Using the Code

Below is a simple HTML file that has an expression {{myIP}} where the IP address will be rendered.

Index.html

HTML
<html>
    <head>
        <title>$http fun</title>
    </head>
    <body ng-app="app">
        <div ng-controller="TestCtrl">
   {{myIP}}
        </div>
        <script type="text/javascript"
        src="https://code.angularjs.org/1.5.0/angular.min.js"></script>
        <script type="text/javascript" src="app.js"></script>
    </body>
</html>

Below is the AngularJS code demonstrating the $http service.

app.js

JavaScript
var app = angular.module('app', []);
app.controller("TestCtrl", function($scope, $http) {
    $http({
            method: 'GET',
            url: 'http://ip.jsontest.com/'
        })
        .then(function(response) {
            $scope.myIP= response.data.ip;
        })
})

The $http can also be invoked in a shortcut form as illustrated below. We will follow this approach for the rest of the examples.

app.js Illustrating Shortcut Way of Using $http

JavaScript
var app = angular.module('app',[]);
app.controller("TestCtrl",function($scope,$http){
  $http.get('http://ip.jsontest.com/')
       .then(function(response){
         $scope.myIP= response.data.ip;
       })
})

Output

Image 1

The above example shows a simple usage of the $http service in AngularJS. The $http is injected to the controller. The $http.get is invoked using the URL supplied. As mentioned above, $http returns a promise object. A promise object has two functions, then and catch. The then function is called when the promise is successful and catch function is called when the promise has some error.

In the above example, the first argument of the then function is invoked, upon success returns the response object. The response object is as below:

{"data":{"ip":"103.255.227.108"},"status":200,"config":{"method":"GET","transformRequest":[null],
"transformResponse":[null],"url":"http://ip.jsontest.com/","headers":{"Accept":"application/json, 
text/plain, */*"}},"statusText":"OK"}

As we are trying to retrieve the IP address, we get it using $scope.myIP= response.data.ip.

Handling Exceptions

To handle a scenario where an exception is thrown, e.g., the case of a 404 error when you access a url, the then function can have an additional argument to handle it.

app.js Illustrating Exception Handling Using Additional Argument in then

JavaScript
var app = angular.module('app',[]);
app.controller("TestCtrl",function($scope,$http){
  $http.get('http://google.co.in/abcd')
       .then(function(response){
         $scope.myIP= response;
       }, function(error){
         $scope.myIP= error.status;
       })
})

Note: The URL is supplied as 'http://google.co.in/abcd' which will return a 404 error.

The catch function can also be used to handle the exception alternatively.

app.js Illustrating Exception Handling Using Catch

JavaScript
var app = angular.module('app', []);
app.controller("TestCtrl", function($scope, $http) {
    $http.get('http://google.com/abcd')
        .then(function(response) {
            $scope.myIP = response.data.ip;
        })
        .catch(function(error) {
            $scope.myIP = error.status;
        })
})

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
I code for fun.

Comments and Discussions

 
-- There are no messages in this forum --