How to use HTTP Get Method ($http.get) in AgularJS
How to use HTTP Get Method ($http.get) in AgularJS
398
27-Nov-2020
Updated on 27-Nov-2020
Anonymous User
27-Nov-2020Hi ,
Here we will create a simple example of $http.get() method in AngularJS.
$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
Syntax for AngularJS v1.4.8 + (v1.5.0)
The response object has following properties
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.
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.
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
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
HomeController.cs
OutPut:
AgularJS HTTP Get Method ($http.get) with Example
I hope this article will help to you.