Saturday, 22 December 2018

What is AngularJS $http service


  
What is AngularJS $http service 

$http service is used for Ajax calls to get data from server or post data to server.

The below example will demonstrate you to use $http in AngularJS.

Example:

<script>
        var myApp = angular.module('myApp', []);

        myApp.controller('EmpController', function ($scope, $http) {

            // the $http service is called to get the data. you need to pass api url to get the data

            $http.get("url/Employeelist")
            .then(function(response) {
                $scope.students = response.data;
            });
        });
</script>

Following are the http service methods

.delete()
.get()
.head()
.jsonp()
.patch()
.post()
.put()

The methods above are all shortcuts of calling the $http service:

Example
<script>
    var myApp = angular.module('myApp', []);
    myApp.controller('EmpController', function ($scope, $http) {
        $http({
            method: "GET",
            url: "url/Employeelist"
        }).then(function mySuccess(res) {
            $scope.data = res.data;
        }, function myError(response) {
            $scope.error = res.statusText;
        });
    });

</script>

Response Properties
The response is an object with these properties:

.config:- this is used to generate the request.
.data:- this can be a string, or an object that holding the response from the server.
.headers:- this is a function to use to get header information.
.status:- It gives the HTTP status number.
.statusText:- this is a string defining the HTTP status

<script>
    var myApp = angular.module('myApp', []);
    myApp.controller('EmpController', function ($scope, $http) {
        $http.get("url/Employeelist")
        .then(function (res) {
            $scope.result = res.data;
            $scope.statuscode = res.status;
            $scope.statusmessage = res.statusText;
            $scope.header = res.headers;
        });
    });

</script>

You can add one more functions to the .then method to handle errors.

<script>
    var myApp = angular.module('myApp', []);
    myApp.controller('EmpController', function ($scope, $http) {
        $http.get("url/Employeelist")
        .then(function (res) {
            $scope.result = res.data;
        }, function (res) {
            //Second function handles error
            $scope.result = "Something went wrong";
        });
    });
</script>