In AngularJS, AJAX (Asynchronous JavaScript and XML) is commonly used to make asynchronous HTTP requests to fetch or send data between the client and the server. AngularJS provides a service called $http for making HTTP requests. Here's a basic overview of how AJAX works with AngularJS:
-
Injecting
$httpService:To use the
$httpservice, you need to inject it into your controller, service, or other AngularJS components.angular.module('myApp').controller('MyController', ['$http', function($http) { // Your controller logic here }]); -
Making GET Requests:
The
$httpservice can be used to make GET requests to retrieve data from a server. For example:$http.get('/api/data') .then(function(response) { // Handle successful response console.log(response.data); }) .catch(function(error) { // Handle error console.error('Error fetching data:', error); }); -
Making POST Requests:
To send data to the server using a POST request:
var data = { key: 'value' }; $http.post('/api/save', data) .then(function(response) { // Handle successful response console.log('Data saved successfully:', response.data); }) .catch(function(error) { // Handle error console.error('Error saving data:', error); }); -
Using Promises:
The
$httpservice returns promises, which allows you to handle asynchronous operations using.then() and .catch(). -
Handling Response:
The response from the server is available in the
thenblock, and you can access the data, status, headers, and other information.$http.get('/api/data') .then(function(response) { console.log('Data:', response.data); console.log('Status:', response.status); console.log('Headers:', response.headers); }) .catch(function(error) { console.error('Error:', error); }); -
Interacting with AngularJS Scope:
You can update the AngularJS scope with the fetched data, allowing it to be automatically reflected in the view.
$http.get('/api/data') .then(function(response) { $scope.myData = response.data; }) .catch(function(error) { console.error('Error fetching data:', error); });
These are the basic steps to perform AJAX requests in AngularJS using the $http service. It's worth noting that in modern versions of Angular (Angular 2 and above), the preferred way to make HTTP requests is using the HttpClient module, which provides a more powerful and flexible API for handling HTTP operations.