Introduction:

In this article we will explain How to get data from Server in AngularJS or what is $http.get() method in  AngularJS or how to use $http.get() in AngularJS with example.

Description:

$http.get() method sends http GET request to the remote server and retrieves the data.  $http.get() method used to get data from remote server  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 remote 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);

 

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

 

$http.get(url,
data)
.then(data,status, headers, config)
.catch(data,status, headers, config);

The response object has following properties

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

 

In below code snippet, we shall see how to easily 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 first function defined  inside the Home controller is GetAllData() that sends request to the server to '/Home/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("HttpGetCtrl", function ($scope, $http) {
            $scope.keyword = '';
            $scope.GetAllData = function () {
                $http.get('/Home/GetData')
                .then(function (data, status,headers, config) {
                    $scope.Details = data['data'];                   
                })
                .catch(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('/Home/GetData', config)
                .then(function (data, status, headers, config) {
                    $scope.Details = data['data']
                   
                })
                .catch(function (data, status,header, config) {
                    $scope.ResponseDetails = "Data: " + data +
                        "<hr />status: " + status +
                        "<hr />headers: " + header +
                        "<hr />config: " + config;
                })                 
            };
        });      
    </script>

The second 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 configobject as  params.  This config object is then passed as second parameter to the $http.get method. The .success and .error function does the same thing that it does in the first function GetData().

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

 

   <div class="container">        
        <div ng-app="app" ng-controller="HttpGetCtrl">
            <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.CustomerName + ' ' + d.Contact + ', ' + d.Email}}
                </li>
            </ul>
            <p ng-bind="ResponseDetails"></p>
            {{ResponseDetails}}
        </div>        
    </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 Home Controller action method.

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

       

[HttpGet]
        public JsonResult GetData(string keyword="")
        {
            ArticleDBEntities db = new ArticleDBEntities();           
 
            List<Customer> list = new List<Customer>();
            if (string.IsNullOrEmpty(keyword))
            {
                list = db.Customer.ToList();
            }
            else
            {
                list = db.Customer.Where(p => p.CustomerName.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.

 

For Example :

 

Index.html

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>http.get</title>    
    <script src="/Scripts/angular.js"></script>
   
    <script>
        var app = angular.module("app", []);
        app.controller("HttpGetCtrl", function ($scope, $http) {
            $scope.keyword = '';
            $scope.GetAllData = function () {
                $http.get('/Home/GetData')
                .then(function (data, status, headers, config) {
                    $scope.Details = data['data'];                   
                })
                .catch(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('/Home/GetData', config)
                .then(function (data, status, headers, config) {
                    $scope.Details = data['data']
                   
                })
                .catch(function (data, status, header, config) {
                    $scope.ResponseDetails = "Data: " + data +
                        "<hr />status: " + status +
                        "<hr />headers: " + header +
                        "<hr />config: " + config;
                })                 
            };
        });      
    </script>
</head>
<body>
    <div class="container">       
        <div ng-app="app" ng-controller="HttpGetCtrl">
            <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.CustomerName + ' ' + d.Contact + ', ' + d.Email}}
                </li>
            </ul>
            <p ng-bind="ResponseDetails"></p>
            {{ResponseDetails}}
        </div>        
    </div>  
</body>
</html>

 

HomeController.cs

 

using MVC_Tutorials.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_Tutorials.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {              return View();
        }
 
        [HttpGet]
        public JsonResult GetData(string keyword="")
        {
            ArticleDBEntities db = new ArticleDBEntities();           
 
            List<Customer> list = new List<Customer>();
            if (string.IsNullOrEmpty(keyword))
            {
                list = db.Customer.ToList();
            }
            else
            {
                list = db.Customer.Where(p => p.CustomerName.StartsWith(keyword)).ToList();
            }
            return Json(list, JsonRequestBehavior.AllowGet);
          
        }
    }     }


OutPut:



i hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

you may also like