Angular.js

AngularJS HTTP Get Example

Hello readers, in this tutorial, we will learn how to implement the angular library $http.get() method in the angular web applications. For this tutorial, we’ll create a sample JSON structure, consume it for reading the data from the web-server, and display the same data in the view.

1. Introduction

AngularJS is a JavaScript MVC or Model-View-Controller framework developed by Google that lets developers build well structured, easily testable, and maintainable front-end applications. The angular library provides multiple out-of-box services and angular ajax is one of them.

The angular framework provides the $http services and is used to do the HTTP request to retrieve the desired data from the server. The server would then make a database call to retrieve the required records in the JSON format. In angular ajax, developers can send the Ajax requests in multiple ways, such as:

  • Angular Ajax calls through $http service
  • JSONP calls through $http service
  • REST API calls
Fig. 1: Ajax request in Angular
Fig. 1: Ajax request in Angular

1.1 What is HTTP service?

$http is the core angular service used to do the HTTP requests to communicate with the remote servers and retrieve the required data through the browser’s XMLHttpRequest object or the JSON. To access the angular ajax in a controller, developers will have to use the $scope object i.e. $http service retrieve the data from the server in the following way.

$http basic syntax

$http({
	method : "GET",
	url : "<sample_url_path>"
}).then(function(response) {
	$scope.jsondata = response.data;
});

Where:

  • The method property defines the ‘GET‘ or the ‘POST‘ operator
  • The url is the URL of the HTTP server to perform the required operations
  • The $http service makes an Ajax call and set the result in the jsondata property. Later, this model object draws the table in HTML

Do note, the $http service returns the success() and failure() promise objects that take call back functions as parameters.

1.1.1 HTTP Service Methods

There are several functions of calling the $http service. Below is the list of built-in functions available with this service.

  • $http.get(url, config): This is frequently used method to read the records from the server
  • $http.post(url, data, config) and $http.put(url, data, config): These methods accept an input argument to be sent to the server in JSON string
  • $http.delete(url, config): This method deletes the record or the information from the server
  • $http.head(url, config): This method allows the client and the server to pass an additional information with the request or the response object

Developers can refer this link to have a detailed information on $http service. These new APIs make developer’s life easier, really! But it would be difficult for a beginner to understand this without an example. Therefore, let us create a simple application using the $http.get() method for reading the server data.

2. AngularJS HTTP Get Example

Here is a step-by-step guide for implementing the $http.get() method in angular applications.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure if you are confused about where you should create the corresponding files or folder later!

Fig. 2: Application Project Structure
Fig. 2: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse Ide, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project
Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 4: Project Details
Fig. 4: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 5: Archetype Selection
Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will enter the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters
Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>AngularJsHttpGet</groupId>
	<artifactId>AngularJsHttpGet</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

Let’s start building the application!

3. Application Building

Let’s create an application to understand the basic building blocks of the $http.get() method in the angular library.

3.1 Load the AngularJS framework

Since it is a pure JavaScript framework, we should add its reference using the <script> tag.

<script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>

3.2 Define the AngularJS application

Next, we will define the angular application using the <ng-app>, <ng-controller>, and <ng-init> directives.

index.jsp

<div ng-app = "myApp" ng-controller="ctrl" ng-init="getData()">
 	.....
</div>

3.3 Creating an AngularJS Controller

The JavaScript file i.e. ang_http_get_data.js includes the ctrl function as the “controller” in the Model-View-Controller. This JavaScript code is retrieving the JSON data from the data.json file using an ajax ask from the server. Here, we are injecting the $http in the angular controller and assigning the response to the json_data list.

ang_http_get_data.js

var app = angular.module("app", []);

app.controller("ctrl", ['$scope', '$http', function($scope, $http) {

	$scope.sortType = 'name'; 		// Set the default sort type
	$scope.sortOrder  = false; 		// Set the default sort order	
	$scope.state  = false;				// Set the default error message state

	$scope.json_data = null; 			// Set the default planet_list

	$scope.getData = function() {
		$http({			
			method: "GET",
			url: 'resource/config/data.json'
		}).then(function(response) {
			$scope.json_data = response.data;
			console.log("Success -> " + response.data);
		}, function(response) {
			$scope.state  = true;
			console.log("Failure");
		});
	};
}]);

3.4 Complete Application

Complete the above steps and I will show you how to use the angular ajax with real-life practices. Let’s see the code snippet.

index.jsp

<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>AngularJS HttpGet</title>
          
      <!-- Angular Javascript File -->
      <script type="text/javascript" src="resource/js/angular_v1.6.0.js"></script>
      <script type="text/javascript" src="resource/js/ang_http_get_data.js"></script>
      
      <!-- Bootstrap Css -->
      <link rel="stylesheet" href="https://www.webcodegeeks.com/wp-content/litespeed/localres/aHR0cHM6Ly9tYXhjZG4uYm9vdHN0cmFwY2RuLmNvbS8=bootstrap/4.0.0/css/bootstrap.min.css">
      <link rel="stylesheet" href="resource/css/planets.css">     
   </head>
   <body>
      <div id="angularHttpGet" class="container">
         <h1 align="center" class="text-primary">AngularJS - HTTP Get Example</h1>
         <hr />
         
         <!------ ANGULAR JS HTTP 'get()' EXAMPLE ------>
         <div ng-app="app" ng-controller="ctrl" ng-init="getData()">
         	<h3 id="header_msg" class="text-warning">A demo of HTTP '<em>get()</em>' method in Angular JavaScript!</h3>
         	<div> </div>
         	         	
         	<table id="planetsTable" class="table" ng-show="!state">
         		<thead>
         			<tr>
         				<th scope="col">Planet Id</th><th scope="col"><a href="#" ng-click="sortType = 'name'; sortOrder = !sortOrder">Planet / Star</a></th><th scope="col">Distance from Sun</th><th scope="col">Light Years</th><th scope="col">Moons Count?</th>
         			</tr>
         		</thead>
         		<tbody>
         			<tr ng-repeat="row in json_data | orderBy:sortType:sortOrder" ng-class="rollClass" ng-mouseenter="rollClass = 'highlight'" ng-mouseleave="rollClass = ''">
         				<td>{{ row.id }}</td>
         				<td>{{ row.name }}</td>
         				<td>{{ row.distancefromsun }}</td>
         				<td>{{ row.lightyears }}</td>
         				<td>{{ row.moons }}</td>
         			</tr>         			    			
         		</tbody>
         	</table> 
         	
         	<!-- Error Message -->
         	<div id="showError" ng-show="state">
         		<span id="failureMsg" class="text-danger">Error in retrieving data!</span>
         	</div>       	         	
         </div>
      </div>
   </body>
</html>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 7: How to Deploy Application on Tomcat
Fig. 7: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page using the angular ajax will be displayed.

http://localhost:8082/AngularHttpGet/

Server name (localhost) and port (8082) may vary as per your Tomcat configuration.

Fig. 8: Application Index page
Fig. 8: Application Index page

If the server URL is not responding, the user will get an error message as shown in Fig. 9.

Fig. 9: Error message
Fig. 9: Error message

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create a simple application using the $http.get() method. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was a tutorial of the $http.get() method in the angular library.

Download
You can download the full source code of this example here: AngularJsHttpGet

Yatin

The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button