October 29, 2015

AngularJS - How to GET and POST data by http methods Get / Post

In this post, we will see how to use http requests in AngularJS. For the scope of this post, I assumed that we have already developed ASP.NET WebAPI, say for Products. So we have a ProductController which have action methods for CRUD operations. Lets see how we call that methods from AngularJS, I am using AngularJS factory method as a service componenet to communicate with server.

For example the following code snippet assumes you have a app module varaible defineds as demoApp, here we are creating a productFactory with a dependency parameter $http which we use to make requests to server.
 
demoApp.factory('productFactory', function ($http) {
}
This is how we create a get request over $http object, we passed a URL to ProductController and calling its Get method, which will return data in json string. We also passed 2 callback functions as parameters, first one is called if the request is successfull and the second will be called if request encountered any error.
$http.get('api/Product/Get').
 success(function (data, status, headers, config) {
  // successfully get json response from server
  console.log("get products list - success");
 }).
 error(function (data, status, headers, config) {
  // log error
  console.log(status);
});
This is how we can create a post request over $http object. First define an object, say config, which will define the request headers or other configuration properties. Here we are passing three parameters to the Post function, first is the URL with Controller's post action method, second is the object we want to pass as parameter/data to that function, third is our configuration object we want to set with this request.
  var config = {
  headers: { 'Content-Type': 'application/json' }
 }

$http.post('api/Product/PostProduct', product, config)
 .then(
  function (response, status, headers, config) {
     //sucessfully posted to server
     console.log('PostProduct success: ' + product.Id);
  },
  function (response, status, headers, config) {         
     //log error
     console.log('PostProduct failed.', response, status, headers);
  }
 );
Similarly following code segment will make a delete http request. Here we are only passing productID as query string parameter to the required URL, i.e. Controller's delete action method will accept an integer variable productID as parameter.
  var params = "productID=" + id;
$http.delete('api/Product/DeleteProduct?' + params)
 .then(
  function (response, status, headers) {
   //sucessfully processed delete request
   console.log('DeleteProduct success: ');
  },
  function (response, status, headers) {
   //log error
   console.log('DeleteProduct failed.', response, status, headers);
  }
 ); 
Hope this post helps you, give an idea how to deal with http methods in AngularJS.

No comments:

Post a Comment