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