Ajax calls are an integral part of modern web applications. Angular provides two different APIs to handle Ajax requests, $http and $resource. They are
- $http
It is an AngularJS service for reading data from remote servers. It SIMPLY makes a request to the server, and returns a response.
$http service methods are listed below:- get()
General syntax:
$http.get(<url>)
Example:12345$http.get("http://axleducation.com /courses").then(function(response){$scope.courses= response.data;});});
Note: Its perfectly fine to use success instead of then if you want the factory to return the original $http promise - post()
General syntax:
$http.post(<url>,<request_data>)
Example:123456789var data = {'name' : 'Priyesh Das'}$http.post("students.php", data ).success(function(response) {$scope.posting = response.data; // response.data is an array}).error(){// Error callback will trigger}); - delete()
$http.delete(url, [config]) - head()
- jsonp()
Example:123456789var data = {'name' : 'priyesh das'}$http.jsonp("student.php", data ).success(function(response) {$scope.jsonp = response.data; // response.data is an array}).error(){// Error callback will trigger});
Config:method – used to set the HTTP method ( GET, POST, PUT, DELETE, HEAD ).URL – Requesting URL.parameter – It is an optional or we can pass additional parameters to destination.headers – to sent additional HTTP headers to the server.timeout – abort the request once the specified waiting time limit is reached.
cache – enable for XHR request cacheing.
Promise Object:
success – If the callback function got succeed, success function will execute.
error – If the Callback function failed, then it will execute.
- patch()
- put()
<div ng-app=”myApp” ng-controller=”AngularCtrl”>
<table>
<tr ng-repeat=”x in topics”>
<td>{{ x.Name }}</td>
<td>{{ x.Description }}</td>
</tr>
</table>
</div>
- get()
- $resource
Angular’s $resource is a factory which creates a resource object that lets you interact with RESTful backends easily. $resource wraps $http for use in RESTful web API scenarios, as REST is a subset of HTTP. The $resource service doesn’t come bundled with the Angular script. You’ll need to download it (“angular-resource.js“) and include it in your project.Syntax:
$resource(url, [paramDefaults], [actions], options)
Returns
A resource “class” object with methods for the default set of resource actions optionally extended with custom actions
Arguments:
a. url
A parameterized URL template with parameters prefixed by :
b. paramDefaults (optional)
Default values for url parameters.
c. actions(optional)
d. options - Third-party libraries
We can also use third-party libraries like Restangular to abstract away pain points of dealing with API responses.