HTTP and AJAX in AngularJS
Key Concepts
- $http Service
- GET Request
- POST Request
- PUT Request
- DELETE Request
- Request Configuration
- Response Handling
- Error Handling
- Interceptors
- Promises and $q Service
1. $http Service
The $http
service in AngularJS is a core service for reading data from web servers and for posting data to remote servers. It is a wrapper around the browser's XMLHttpRequest
object.
Example:
app.controller('MyController', function($scope, $http) { $http.get('/api/data') .then(function(response) { $scope.data = response.data; }); });
Imagine $http
as a courier service that fetches packages (data) from a remote warehouse (server) and delivers them to your doorstep (controller).
2. GET Request
A GET request is used to retrieve data from a specified resource. It is the most common HTTP method and is used to read or retrieve data.
Example:
$http.get('/api/data') .then(function(response) { $scope.data = response.data; });
Think of a GET request as a librarian retrieving a book (data) from a shelf (server) based on a specific query (URL).
3. POST Request
A POST request is used to submit data to be processed to a specified resource. It is often used to create new resources.
Example:
$http.post('/api/data', {name: 'John', age: 30}) .then(function(response) { $scope.result = response.data; });
Consider a POST request as mailing a letter (data) to a recipient (server) to create a new record (resource) in their database.
4. PUT Request
A PUT request is used to update a resource at a specified location. It replaces the entire resource with the new data provided.
Example:
$http.put('/api/data/1', {name: 'John', age: 31}) .then(function(response) { $scope.result = response.data; });
Think of a PUT request as updating a book (resource) in a library (server) with a new edition (data).
5. DELETE Request
A DELETE request is used to delete a specified resource. It removes the resource from the server.
Example:
$http.delete('/api/data/1') .then(function(response) { $scope.result = response.data; });
Consider a DELETE request as removing a book (resource) from a library (server) permanently.
6. Request Configuration
Request configuration allows you to customize the HTTP request by specifying headers, parameters, and other options.
Example:
$http({ method: 'GET', url: '/api/data', headers: {'Authorization': 'Bearer token'}, params: {page: 1} }).then(function(response) { $scope.data = response.data; });
Imagine request configuration as customizing a delivery package (request) with specific labels (headers) and instructions (parameters).
7. Response Handling
Response handling involves processing the data returned from the server. The response object contains data, status, and headers.
Example:
$http.get('/api/data') .then(function(response) { $scope.data = response.data; $scope.status = response.status; });
Think of response handling as receiving a package (response) and inspecting its contents (data) and delivery status (status).
8. Error Handling
Error handling is crucial for managing failures in HTTP requests. It allows you to catch and handle errors gracefully.
Example:
$http.get('/api/data') .then(function(response) { $scope.data = response.data; }) .catch(function(error) { $scope.error = error.data; });
Consider error handling as having a backup plan (catch block) for when a package (request) is lost (fails) during delivery.
9. Interceptors
Interceptors are used to intercept HTTP requests and responses. They can modify requests and responses, add headers, or handle errors globally.
Example:
app.factory('myInterceptor', function($q) { return { request: function(config) { config.headers['Authorization'] = 'Bearer token'; return config; }, responseError: function(rejection) { return $q.reject(rejection); } }; }); app.config(function($httpProvider) { $httpProvider.interceptors.push('myInterceptor'); });
Imagine interceptors as security checkpoints (interceptors) that inspect and modify packages (requests/responses) before they reach their destination.
10. Promises and $q Service
Promises and the $q
service are used to handle asynchronous operations in AngularJS. They provide a way to manage the flow of asynchronous code.
Example:
app.controller('MyController', function($scope, $http, $q) { var promise = $http.get('/api/data'); promise.then(function(response) { $scope.data = response.data; }); });
Think of promises as a guarantee (promise) that a package (data) will be delivered (resolved) or an issue will be reported (rejected) in the future.