Tuesday, 21 March 2017

How to use $http service to make HTTP requests ?


$http is a built-in service which takes a configuration object as parameter.
All properties supported : https://docs.angularjs.org/api/ng/service/$http#usage

Example
$http({
   method: 'GET',
   url: 'EmployeeService/GetAllEmployees'
});



JS (Using get method of $http)
Without then function
app.controller("myController", function ($scope, $http) {
  
$scope.employees = $http.get('EmployeeService/GetAllEmployees');
});

With then function
app.controller("myController", function ($scope, $http) {
   $http.get('
EmployeeService/GetAllEmployees')
        .then( function(response) {
           $scope.employees = response.data;
        });
});



JS (Using $http service as a function)
app.controller("myController", function ($scope, $http) {
   $http( { 

       method: 'GET',
       url:'EmployeeService/GetAllEmployees' })
   .then( function(response) {
       $scope.employees = response.data; 
   });
});



Multiple functions to handle success and error callbacks
app.controller("myController", function ($scope, $http) {
   $http.get('
EmployeeService/GetAllEmployees')
        .then( function(response) {
                   $scope.employees = response.data;
               } ,
function(reason) {
                   $scope.error = reason.data;
               } );
});


OR

app.controller("myController ", function ($scope, $http) {
   var successFunc = function (response) {

       $scope.employees = response.data;
   }

   var errorFunc = function (reason) {
       $scope.error = reason.data;
   }

   $http.get('EmployeeService/GetAllEmployees').then(successFunc, errorFunc);

});
OR

   $http({
       method: 'GET',
       url: 'EmployeeService/GetAllEmployees'
   })
   .then(successFunc, errorFunc);

No comments:

Post a Comment

Note: only a member of this blog may post a comment.