articles

Home / DeveloperSection / Articles / HTTP Communication in AngularJS

HTTP Communication in AngularJS

HTTP Communication in AngularJS

Ashutosh Kumar Verma 159 25-Jun-2024

AngularJS http Communication

In AngularJS, HTTP connections are mainly handled using the $http service, which allows data to be sent and received from a remote server. The $http service is a basic AngularJS service that provides a simple interface for processing HTTP requests and responses.

Here is a simple guide on how to make an HTTP connection in AngularJS using the $http implementation,

 

Configure the AngularJS application

First, you need to add AngularJS to your project. You can do this by adding an AngularJS library to your HTML file.

<!DOCTYPE html>
<html ng-app="myApp">
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
   <div ng-controller="MainController">
       <!-- Your content goes here -->
   </div>
   <script src="app.js"></script>
</body>
</html>

 

Create the AngularJS Application Module and Controller

Next, create an AngularJS module and controller. On the controller, it will use the $http service to make HTTP requests.

angular.module('myApp', [])
  .controller('MyController', function ($scope, $http) {
    // making http get request
    $scope.getData = function() {
      $http.get('https://api.example.com/data')
          .then(function(response) {
              // Handle response if data fetched successfully
              $scope.data = response.data;
          }, function(error) {
              // Handle if any error occured
              console.error('Error:', error);
          });
    };
    // making http post request
    $scope.postData = function() {
      var data = {
          key: 'value'
      };
      $http.post('https://api.example.com/data', data)
          .then(function(response) {
              // Handle response if data saved successfully
              $scope.response = response.data;
          }, function(error) {
              // Handle if any error occured
              console.error('Error:', error);
          });
    };
  });

 

Performing an HTTP GET request

The $http.get method is used to make an HTTP GET request. It takes this URL as a parameter and returns a promise.

$http.get('https://api.example.com/data')
   .then(function(response) {
       // Handle success
       $scope.data = response.data;
   }, function(error) {
       // Handle error
       console.error('Error:', error);
   });

 

Creating an HTTP POST Request

The $http.post method is used to make an HTTP POST request. It takes a URL and a data item as parameters and returns a promise.

var data = {
   key: 'value'
};
$http.post('https://api.example.com/data', data)
   .then(function(response) {
       // Handle success
       $scope.response = response.data;
   }, function(error) {
       // Handle error
       console.error('Error:', error);
   });

 

Handling Promises

The $http function returns a promise, which can be processed using the .then() method for both success and failure cases. The .then() method takes two functions as parameters: if the request succeeds, the first operation is executed, and if the request fails, the second operation is executed

 

Also, Read: Form validation in AngularJS

 

Additional HTTP Methods

The $http service supports other HTTP methods such as PUT, and DELETE.

HTTP ‘PUT’ request

var data = {
   key: 'new value'
};
$http.put('https://api.example.com/data/1', data)
   .then(function(response) {
       // Handle success
       $scope.response = response.data;
   }, function(error) {
       // Handle error
       console.error('Error:', error);
   });

HTTP ‘DELETE’ request

$http.delete('https://api.example.com/data/1')
   .then(function(response) {
       // Handle success
       $scope.response = response.data;
   }, function(error) {
       // Handle error
       console.error('Error:', error);
   });

 

Configuring Requests

You can also configure the request by passing a configuration object to the $http path. The configuration object allows you to configure titles, parameters, and other options.

$http({
   method: 'GET',
   url: 'https://api.example.com/data',
   params: { id: 1 },
   headers: {
       'Authorization': 'Bearer token'
   }
}).then(function(response) {
   // Handle success
   $scope.data = response.data;
}, function(error) {
   // Handle error
   console.error('Error:', error);
});

You can also use the above $http({…})methods for HTTP communication in AngularJS application.

The $http function in AngularJS is a powerful tool to handle HTTP connections in your application.

 

Also, Read: Fetch Data from RESTFul APIs in AngularJS

 

 

 

 

 


Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By