Server side communication in Angular
Server-side communication in angular is done via the below modes:
Using built in $http service
Using the Restangular library
$http service: Simply stating $http service is a wrapper around browsers native XMLHttpRequest (XHR) object or may use the JSONP (JSON padding) mode for interacting using HTTP. It is a function which expects single object parameter for configuration and returns a Promise.
A typical example of a $http function to interact with server is as below:
$http({
method : ‘GET’,
url : ‘/api/users.json’
}).success(function (data, status, headers, config) {
// This is called for successful response
}).error(function (data, status, headers, config) {
// This is called when the erroneous response
});
Normally the $http method won’t execute until the next digest loop runs. To force the $http method to run outside of the digest loop explicitly, we may use the $apply block as below:
$scope.$apply(function () {
$http({
method : 'GET',
url : '/api/users.json'
});
});
$http shortcut methods: The $http service also provides shortcut methods, the complete list of which is given below: [Reference: $http]
Configuration object parameter: The configuration object parameter passed to the $http service method has the following set of possible parameters:
method (string): The HTTP method on server being called. Expected values are ‘GET’, ‘DELETE’ , ‘HEAD’ , ‘JSONP’, ‘POST’, ‘PUT’
url (string): The url of the server resource being requested
params: This iseither astring combination which is converted into query string or an object which is JSONified to be sent to server.E.g.
$http({
params: {'key': 'value'}
});
data: the data that will be POSTed
Along with the above, there are other options which are used less frequently
We will see the $resource and Restangular in the next part along with other server side communication tricks available as part of Angular