In AngularJS, $http
is the service used to make HTTP requests to communicate with a backend server or API. It provides a simple and efficient way to send GET, POST, PUT, and DELETE requests, which are the common HTTP methods used in CRUD (Create, Read, Update, Delete) operations. Below is a detailed explanation of how to use $http
to send each type of request.
1. $http GET Request
The GET request is used to retrieve data from a server. In AngularJS, you can use the $http.get()
method to make GET requests.
Example: Sending a GET Request
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
// Make a GET request to fetch data
$http.get('/api/data')
.then(function(response) {
// Success: Handle the response data
$scope.data = response.data;
})
.catch(function(error) {
// Error: Handle the error
console.error("Error fetching data:", error);
});
});
Explanation:
$http.get('/api/data')
: Sends a GET request to the specified URL (/api/data
)..then()
: The.then()
function is used to handle the success response..catch()
: The.catch()
function is used to handle errors.
2. $http POST Request
The POST request is used to send data to the server. It is often used to create a new resource on the server. In AngularJS, you can use $http.post()
to send a POST request.
Example: Sending a POST Request
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.submitData = function() {
// Define the data to be sent in the POST request
const data = {
name: $scope.name,
age: $scope.age
};
// Make a POST request to send data to the server
$http.post('/api/data', data)
.then(function(response) {
// Success: Handle the server's response
console.log("Data submitted successfully:", response);
})
.catch(function(error) {
// Error: Handle the error
console.error("Error submitting data:", error);
});
};
});
Explanation:
$http.post('/api/data', data)
: Sends a POST request to the specified URL (/api/data
) with the data object.- The data is sent in the request body.
3. $http PUT Request
The PUT request is used to update an existing resource on the server. In AngularJS, you can use $http.put()
to send a PUT request.
Example: Sending a PUT Request
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.updateData = function() {
const updatedData = {
id: $scope.id,
name: $scope.name,
age: $scope.age
};
// Make a PUT request to update existing data
$http.put('/api/data/' + $scope.id, updatedData)
.then(function(response) {
// Success: Handle the response
console.log("Data updated successfully:", response);
})
.catch(function(error) {
// Error: Handle the error
console.error("Error updating data:", error);
});
};
});
Explanation:
$http.put('/api/data/' + $scope.id, updatedData)
: Sends a PUT request to the specified URL (/api/data/{id}
) to update the data of the resource identified byid
.- The
updatedData
is sent in the request body to update the existing resource.
4. $http DELETE Request
The DELETE request is used to remove a resource from the server. In AngularJS, you can use $http.delete()
to send a DELETE request.
Example: Sending a DELETE Request
angular.module('myApp', [])
.controller('MainController', function($scope, $http) {
$scope.deleteData = function(id) {
// Make a DELETE request to remove data
$http.delete('/api/data/' + id)
.then(function(response) {
// Success: Handle the response
console.log("Data deleted successfully:", response);
})
.catch(function(error) {
// Error: Handle the error
console.error("Error deleting data:", error);
});
};
});
Explanation:
$http.delete('/api/data/' + id)
: Sends a DELETE request to the specified URL (/api/data/{id}
) to delete the resource identified byid
.
Handling Responses
Each $http
request (GET, POST, PUT, DELETE) returns a promise, which resolves to a response object. This response object contains the following important properties:
data
: The data returned from the server.status
: The HTTP status code (e.g., 200 for success, 404 for not found).statusText
: The HTTP status message.headers()
: A function that returns the response headers.
Example: Handling Response
$http.get('/api/data')
.then(function(response) {
console.log("Success:", response.data);
})
.catch(function(error) {
console.error("Error:", error);
});
Using $http
with Configurations
You can configure your $http
requests further by using an optional configuration object. This configuration allows you to set parameters such as custom headers, timeouts, and other options.
Example: Custom Headers and Timeout
$http({
method: 'POST',
url: '/api/data',
data: { name: 'John Doe', age: 30 },
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
},
timeout: 5000 // Timeout after 5 seconds
})
.then(function(response) {
console.log("Data submitted successfully:", response);
})
.catch(function(error) {
console.error("Error submitting data:", error);
});
Explanation:
headers
: Custom headers (e.g.,Authorization
).timeout
: Timeout for the request (in milliseconds).
Error Handling
It’s important to handle errors effectively, especially for operations like DELETE or PUT. The .catch()
method helps in handling errors when the HTTP request fails (e.g., network issues, server errors).
Example: Error Handling
$http.get('/api/data')
.then(function(response) {
// Success: Handle the response
console.log("Data fetched successfully:", response);
})
.catch(function(error) {
// Error: Handle the error
console.error("Error fetching data:", error);
if (error.status === 404) {
console.error("Data not found");
}
});