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:
$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.javascriptapp.controller('MyController', function($scope, $http) {
// Your controller code here
});
javascript$http.get('/api/data').then(function(response) {
// Handle successful response
$scope.data = response.data;
}, function(error) {
// Handle error
console.error('Error:', error);
});
javascriptvar requestData = {
// Your request data
};
$http.post('/api/data', requestData).then(function(response) {
// Handle successful response
}, function(error) {
// Handle error
console.error('Error:', error);
});
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);
});
You can also pass additional configurations such as headers or request parameters:
javascriptvar 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);
});
$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.