How to use $http service for AJAX requests in AngularJS



Image not found!!

In AngularJS, the $http service is used for making AJAX requests to fetch data from a server. Here's a basic guide on how to use $http service:

  1. Inject $http service: First, make sure you inject the $http service into your AngularJS controller, service, or directive where you want to make the AJAX request.
javascript
app.controller('MyController', function($scope, $http) { // Your controller code here });
  1. Make a GET request:
javascript
$http.get('/api/data').then(function(response) { // Handle successful response $scope.data = response.data; }, function(error) { // Handle error console.error('Error:', error); });
  1. Make a POST request:
javascript
var requestData = { // Your request data }; $http.post('/api/data', requestData).then(function(response) { // Handle successful response }, function(error) { // Handle error console.error('Error:', error); });
  1. Make other types of requests:

Similarly, you can use other HTTP methods like PUT, DELETE, PATCH, etc., using $http.put(), $http.delete(), and $http.patch() respectively.

javascript
$http.put('/api/data', updatedData).then(function(response) { // Handle successful response }, function(error) { // Handle error console.error('Error:', error); });
  1. Pass headers and config:

You can also pass additional configurations such as headers or request parameters:

javascript
var config = { headers: { 'Content-Type': 'application/json' }, params: { // Request parameters } }; $http.get('/api/data', config).then(function(response) { // Handle successful response }, function(error) { // Handle error console.error('Error:', error); });
  1. Use Promises: $http service returns a promise, which allows you to handle asynchronous operations in a more elegant way using .then().

Remember, $http is a core AngularJS service, so it's always available once you've injected it into your AngularJS application.

That's a basic overview of using the $http service for AJAX requests in AngularJS.