Using $http for AJAX requests in AngularJS

Loading

In AngularJS, the $http service is used for making AJAX (Asynchronous JavaScript and XML) requests to a server. It allows fetching data from a RESTful API, sending data to a server, and handling HTTP responses efficiently.


1. What is $http in AngularJS?

The $http service in AngularJS is a built-in service that provides an interface to make HTTP requests such as:

  • GET – Fetch data from a server
  • POST – Send data to a server
  • PUT – Update existing data
  • DELETE – Remove data from a server

2. Basic Syntax of $http

The general syntax of $http is:

$http({
method: 'METHOD_TYPE',
url: 'API_ENDPOINT',
data: { /* Data to send in request body */ }
}).then(function successCallback(response) {
// Handle successful response
}, function errorCallback(response) {
// Handle error response
});

Where:

  • method – HTTP method (GET, POST, PUT, DELETE).
  • url – API endpoint.
  • data – Data to send (for POST and PUT).
  • then() – Handles success (response.data) and failure (response.status).

3. Making HTTP Requests with $http

a) GET Request – Fetching Data

app.controller("MyController", function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
$scope.posts = response.data; // Store the fetched data in scope
})
.catch(function(error) {
console.error("Error fetching data:", error);
});
});

Use Case: Fetching a list of posts from an API.


b) POST Request – Sending Data

app.controller("MyController", function($scope, $http) {
$scope.newPost = { title: "AngularJS", body: "Learning AngularJS" };

$scope.addPost = function() {
$http.post("https://jsonplaceholder.typicode.com/posts", $scope.newPost)
.then(function(response) {
console.log("Post added:", response.data);
})
.catch(function(error) {
console.error("Error posting data:", error);
});
};
});

Use Case: Submitting a form or adding new data.


c) PUT Request – Updating Data

app.controller("MyController", function($scope, $http) {
let updatedData = { title: "Updated Title", body: "Updated Body" };

$http.put("https://jsonplaceholder.typicode.com/posts/1", updatedData)
.then(function(response) {
console.log("Data updated:", response.data);
})
.catch(function(error) {
console.error("Error updating data:", error);
});
});

Use Case: Editing existing records.


d) DELETE Request – Removing Data

app.controller("MyController", function($scope, $http) {
$http.delete("https://jsonplaceholder.typicode.com/posts/1")
.then(function(response) {
console.log("Data deleted successfully");
})
.catch(function(error) {
console.error("Error deleting data:", error);
});
});

Use Case: Deleting an item from a list.


4. Handling Errors with $http

Always handle errors using .catch() to avoid application crashes.

$http.get("https://jsonplaceholder.typicode.com/posts")
.then(function(response) {
$scope.data = response.data;
})
.catch(function(error) {
console.error("Error fetching data:", error.status, error.statusText);
});

🔹 Common HTTP Errors:

  • 400 – Bad Request
  • 401 – Unauthorized
  • 404 – Not Found
  • 500 – Server Error

5. Using $http with Promises

Instead of using .then(), you can use AngularJS’s $q service for handling multiple requests.

app.controller("MyController", function($scope, $http, $q) {
function fetchData() {
let request1 = $http.get("https://jsonplaceholder.typicode.com/posts");
let request2 = $http.get("https://jsonplaceholder.typicode.com/users");

$q.all([request1, request2]).then(function(results) {
$scope.posts = results[0].data;
$scope.users = results[1].data;
}).catch(function(error) {
console.error("Error fetching data:", error);
});
}

fetchData();
});

Use Case: Fetching data from multiple APIs at the same time.


6. Configuring Headers in $http

You can send custom headers like authentication tokens.

$http({
method: 'GET',
url: 'https://api.example.com/data',
headers: {
'Authorization': 'Bearer your_token_here',
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log("Data received:", response.data);
});

Use Case: Sending authentication tokens for secure APIs.


7. Caching Requests

To enable caching in $http requests:

$http.get("https://jsonplaceholder.typicode.com/posts", { cache: true })
.then(function(response) {
console.log("Cached Data:", response.data);
});

Use Case: Reducing repeated API calls and improving performance.

Leave a Reply

Your email address will not be published. Required fields are marked *