Home » JavaScript » Angular.js » Remote Access with $http service using AngularJS

About Rajeev Hathi

Rajeev Hathi
Rajeev is a senior Java architect and developer. He has been designing and developing business applications for various companies (both product and services). He is co-author of the book titled 'Apache CXF Web Service Development' and shares his technical knowledge through his blog platform techorgan.com

Remote Access with $http service using AngularJS

Many a times you want to make an asynchronous invocation to the remote server from the client side JavaScript code. This can be achieved through the use of $http service. The article will demonstrate the basic use of $http service in AngularJS

Think remote invocation, think $http. The $http service very neatly abstracts XMLHttpRequest object of the browser to enable you to perform remote invocations. It allows you to make a request to remote services in an AJAX style. The $http service can be directly injected in the controller or you could write your own custom service that can make use of $http service. Here is a quick code snippet that uses $http:

angular.module('myApp.services',[]).service('courseService',
    function($http) {
	this.getCourse = function() {
	    return $http({method:'GET',url:'http://my-domain:8000/course/'});
	}
    });

The courseService makes use of $http service that takes http request method and url as parameters. These parameters are defined as part of config object. We will discuss the config object shortly. You should note that $http pretty much models on $q service and returns you the promise object.

For more information on $q and promise object, you can read here. As with promise object, you could then make use of then() function that will take success and error callbacks as parameters. These callbacks will be called based on whether promise is resolved with success or rejected with error. The below code shows how the promise object returned from $http is handled.

angular.module('myApp.controllers', []).
  controller('MyController', function($scope, courseService) {
      $scope.getCourse = function() {
          courseService.getCourse().then(function(data) {
  	      $scope.result = data.data;
	  }, function(data) {
	      $scope.result = data.status;
	  });
      }
});

Once the request is processed using $http, it invokes either success callback or error callback based on whether the request returned successfully or not. All this happens asynchronously. The data parameter passed to these callback functions is an object that contains the following properties:

data: It is a response from the server
status: It is an http status code (like 404, 200 etc)
config: It is an object that was passed as a request parameter to the $http function
headers: It is an object that contains headers returned by the server

If you find the usage of then() function bit confusing, then you have the option to use success() and error() handler methods. See the example below that uses success() and error callbacks.

angular.module('myApp.controllers', []).
  controller('MyController', function($scope, courseService) {
	$scope.getCourse = function() {
		courseService.getCourse().success(function(data, status, , headers) {
			$scope.result = data;
		}).error(function(data, status, config, headers) {
			$scope.result = status;
		});
	}
});

What’s in the config object

The config object is the object that is passed as a parameter to the $http service. It represents http request and contains various http properties that can be set as part of the request.
Some of the important properties are:

url: This is the request url to the server resource. $http does not allow cross domain invocation. If you want to access remote server that has a different domain name then the server should have the Access-Control-Allow-Origin response header set.
method: The is the http request method. The typical values are either POST or GET. But you could also use values like PUT, DELETE or other forms depending on what you want to achieve with the request.
data: This is the request body. It is typically passed alongside http methods like POST or PUT. The data can be a simple string or an object.
headers: A map object that takes key value as request headers.
params: This is typically used with http method GET for passing query parameters which goes as part of URL.

The below example shows URL query parameters and headers passed as part of config object.

angular.module('myApp.services',[]).service('courseService',
    function($http) {
	this.getCourse = function() {
	    return $http({method:'GET',url:'http://my-domain:8000/course/',
			params: {title:'Science'}, 
			headers: {'Content-Type': 'text/plain'}
                });
	}
    });

There are many other http properties associated with the config object. You could use them to suit your requirement.

$http made easy

There are other short-cut methods available with the $http service. They are as follows:

$http.get()
$http.post()
$http.put()
$http.delete()
$http.head()

All of the above methods takes URL as a parameter. The method post() and put() also takes additional request data parameter.

angular.module('myApp.services',[]).service('courseService',
    function($http) {
        this.getCourse = function() {
	    return $http.get('http://my-domain:8000/course/');
	}
    });

The $http service can be used for making REST style invocations. Its power is simplicity with which one can interact with the remote server.

Reference: Remote Access with http service using AngularJS from our WCG partner Rajeev Hathi at the TECH ORGAN blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments