AngularJS > $http service

$http.get server request in AngularJS

How to get data from Server in AngularJS?


To get data from server asynchrnously in AngularJS, we use $http service. $http service has many shortcut methods depending on which type of request we want to send to the server.

To get the data from server, we use $http.get shortcut method and the signature of this method is below

Syntax of $http.get

The syntax of $http.get method is following

Syntax for AngularJS v1.3.20

$http.get(url, data)
.success(data, status, headers, config)
.error(data, status, headers, config);


Where

  1. url - is url to send request to
  2. data - is data to send along with the request

Syntax for AngularJS v1.4.8 + (v1.5.0)

$http.get(url, config)
   .then(
       function(response){
         // success callback
       },
       function(response){
         // failure call back
       }
    );

The response object has following properties

  1. data - it can be either string or an object (inserted object)
  2. status - HTTP status ode
  3. headers - header information
  4. config - configuration that was used to send request
  5. statusText - response of HTTP status text

In below code snippet, we shall see how to simply make a get server request and then how to make get server request and additionally send data to  the server.

Server call using $http.get

In below <script> block

the 1st function defined inside the controller is GetAllData() that sends request to the server to '/ServerRequest/GetData' url and if the request is successful, set the response data 'data' into $scope.Details property. If error, occures, then the returned data, status and other details are set into $scope.ResponseDetails property.

<script>
    var app = angular.module("app", []);
    app.controller("HttpGetController", function ($scope, $http) {
        
        $scope.keyword = '';

        $scope.GetAllData = function () {
            $http.get('/ServerRequest/GetData')
            .success(function (data, status, headers, config) {
                $scope.Details = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<br />status: " + status +
                    "<br />headers: " + jsonFilter(header) +
                    "<br />config: " + jsonFilter(config);
            });
        };

        $scope.SearchData = function () {

            var parameters = {
                keyword: $scope.keyword
            };
            var config = {
                params: parameters
            };

            $http.get('/ServerRequest/GetData', config)
            .success(function (data, status, headers, config) {
                $scope.Details = data;
            })
            .error(function (data, status, header, config) {
                $scope.ResponseDetails = "Data: " + data +
                    "<hr />status: " + status +
                    "<hr />headers: " + header +
                    "<hr />config: " + config;
            });
        };

    });
</script>

The 2nd function defined in the controller is SearchData() that is responsible to send a get request to the server along with keyword retrieved from the text box whose ng-model is set as $scope.keyword.

To send the data to the server, first we need to prepare an object. As in this case, we need to send only one data (keyword) to the server so the parameters variable contains only one property (to send more data, we can write more properties separated by comma). The same is being set into config object as params.  This config object is then passed as 2nd parameter to the $http.get method. The .success and .error function does the same thing that it does in the 1st function GetData().

Below is HTML code block that sends request to the server.

<div ng-app="app" ng-controller="HttpGetController">
    <button ng-click="GetAllData()">Get All Data</button> |
    <input type="text" name="keyword" ng-model="keyword" required />
    <button ng-click="SearchData()">Search</button>
    <hr />
    <ul>
        <li ng-repeat="d in Details">
            {{ d.FirstName + ' ' + d.LastName + ', ' + d.Age}}
        </li>
    </ul>
    <p ng-bind="ResponseDetails"></p>
    {{ResponseDetails}}
</div>

In above HTML code, first button calls GetData() function on click of first button. The second button, calls SearchData() function that uses keyword text box to send keyword to the server. In both cases, the JSON data is returned from the server. Below is the code snippet of the ASP.NET MVC Controller action method.

ASP.NET MVC with C# code for the server method

        public JsonResult GetData(string keyword)
        {
            List<PersonalDetail> list = new List<PersonalDetail>();
            if (string.IsNullOrEmpty(keyword))
            {
                list = db.PersonalDetails.ToList();
            }
            else
            {
                list = db.PersonalDetails.Where(p => p.FirstName.StartsWith(keyword)).ToList();
            }
            return Json(list, JsonRequestBehavior.AllowGet);
        }

Once the request is processed successfully, The returned data is set into $scope.Details property that is iterated through ng-repeat direcrtive.

As in this case, we have sent only "keyword" from the client to the server. In case, we have sent multiple data to the server, we can retrieve those using Request.QueryString["keyName"].

The output of the above code snippet, looks like this

Output

$http get service in AngularJS

NOTE: The demo may not work properly here as this server doesn't contain GetData() method.

 Views: 194196 | Post Order: 59




Write for us






Hosting Recommendations