AngularJS $http Services

AngularJS Using $http services

AngularJS $http is a core service that communicate with the remote HTTP servers through the browser's XMLHttpRequest object or JSONP (JSON with Padding).

Without using $http service in the AngularJS Web Application, it is like using wooden sword in battle. Mainly $http service is used to do CRUD (Create, Update and Delete) operations in database. It is the most important part to retrieve the JSON data from servers and display in HTML pages.

Syntax

// Simple POST request
$http({
  method: 'POST',
  url: 'http://www.xyz.com/getProducts',
  headers: {
   'Content-Type': application/json
 },
 data: { category: 'fruits' }
})
.then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

// Shortcut method
$http.get('http://www.xyz.com/getProducts', config).then(successCallback, errorCallback);
$http.post('http://www.xyz.com/getProducts', data:{category:'fruits'}, config).then(successCallback, errorCallback);

Will return the response object with following properties.

  • config
  • headers
  • status - 200 to 299 code considered as success, outside these range is considered as error status
  • statusText
  • data - returns JSON {string|Object}

Example

/*
app.js
angularjs $http service
*/
'use strict';

angular.module('myApp', [])

.controller("httpController", ['$scope', '$http', function($scope, $http) {
  $scope.services = [
    {ID:1, name: 'Get IP', url:'https://api.ipify.org?format=json'},
    {ID:2, name: 'Get Geo Information', url:'http://services.groupkt.com/state/get/'},
    {ID:3, name: 'Get Weather - Will get Error', url:'http://api.openweathermap.org/data/2.5/weather?q=London,uk'}
  ];

  $scope.selectedService = {};
  $scope.selectService = function(selected) {
    $scope.response = {};

    if (selected != undefined && selected != null) {
      $scope.selectedService = selected;

      if(selected.ID == 2) {
        $scope.countries = {};
        $http.get('http://services.groupkt.com/country/get/all')
        .then(
          function successCallback(response) {
            $scope.countries = response.data.RestResponse.result;
          }, function errorCallback(response) {
            $scope.response = response;
        });
      }
    }
  };

  $scope.ip = '';
  $scope.getIP = function() {
    $http.get($scope.selectedService.url)
    .then(
      function successCallback(response) {
        $scope.response = response;
        $scope.ip = response.data.ip;
      }, function errorCallback(response) {
        $scope.response = response;
      });
  };

  $scope.states = {};
  $scope.getStates = function(selected) {
    if (selected != undefined && selected != null) {
      $http.get($scope.selectedService.url + selected.alpha3_code + '/all')
      .then(
        function successCallback(response) {
          $scope.response = response;
          $scope.states = response.data.RestResponse.result;
        }, function errorCallback(response) {
          $scope.response = response;
      });
    }
  };

  $scope.getWeather = function() {
    $http.get($scope.selectedService.url)
    .then(
      function successCallback(response) {
        $scope.response = response;
      }, function errorCallback(response) {
        $scope.response = response;
      });
  };
}]);
<!DOCTYPE html>
<!--
index.html
angularjs $http service
using ng-model, ng-options, ng-change, ng-hide, ng-click, ng-repeat and ng-class directives.
-->
<html ng-app="myApp">
<head>
  <title>AngularJS using $http service example</title>

  <!-- bootsrap CDN -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
</head>
<body>
  <div class="container" ng-controller="httpController">
    <div class="row">
      <div class="col-md">
        Select Service:
        <select class="form-control" ng-model="selectedService" ng-options="service.name for service in services" ng-change="selectService(selectedService)">
          <option value="">Select Service</option>
        </select>
        <h4>Service url: {{selectedService.ID != 2 ? selectedService.url : selectedService.url + selectedCountry.alpha3_code}}</h4>
      </div>
    </div>
    <br>
    <div class="row">
      <div class="col-md bg-white" ng-hide="selectedService.ID == 1 ? false : true">
        <h3>Your IP is <b>{{ip}}</b></h3>
        <input type="button" class="btn btn-success" value="Get IP" ng-click="getIP()">
      </div>
      <div class="col-md bg-white" ng-hide="selectedService.ID == 2 ? false : true">
        <h4>Get States of selected country (Only INDIA and USA available)</h4>
        <select class="form-control" ng-model="selectedCountry" ng-options="country.name for country in countries" ng-change="getStates(selectedCountry)">
          <option value="">Select Country</option>
        </select>
        <h4>States</h4>
        <table class="table table-striped table-bordered">
          <thead>
            <tr>
              <th>Name</th>
              <th>Abbr</th>
              <th>Area</th>
              <th>Capital</th>
              <th>Largest City</th>
            </tr>
          </thead>
          <tbody>
            <tr ng-repeat="state in states">
              <td>{{state.name}}</td>
              <td>{{state.abbr}}</td>
              <td>{{state.area}}</td>
              <td>{{state.capital}}</td>
              <td>{{state.largest_city}}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="col-md bg-white" ng-hide="selectedService.ID == 3 ? false : true">
        <input type="button" class="btn btn-success" value="Get Weather" ng-click="getWeather()">
      </div>
    </div>
    <br>
    <div class="row">
      <div class="col-md">
        <ul style="list-style:none">
          <li><b>Response</b></li>
          <li><b>data:</b> {{response.data}}</li>
          <li><b>satus:</b> <span ng-class="{'text-danger': response.status >= 200 && response.status <=299 && response.status != '' ? false : true}">{{response.status}}</span></li>
          <li><b>config:</b> {{response.config}}</li>
          <li><b>headers:</b> {{response.config.headers}}</li>
          <li><b>statusText:</b> <span ng-class="{'text-danger': response.status >= 200 && response.status <=299 && response.status != '' ? false : true}">{{response.statusText}}</span></li>
        </ul>
      </div>
    </div>
  </div>

  <!-- AngularJS CDN -->
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
  <script src="app.js" type="text/javascript"></script>
</body>
</html>
Select Service:

Service url: {{selectedService.ID != 2 ? selectedService.url : selectedService.url + selectedCountry.alpha3_code}}


Your IP is {{ip}}

Get States of selected country (Only INDIA and USA available)

States

Name Abbr Area Capital Largest City
{{state.name}} {{state.abbr}} {{state.area}} {{state.capital}} {{state.largest_city}}

  • Response
  • data: {{response.data}}
  • satus: {{response.status}}
  • config: {{response.config}}
  • headers: {{response.config.headers}}
  • statusText: {{response.statusText}}