Work with HTTP Service in AngularJS

Lakshitha Kumara
5 min readFeb 23, 2021

Introduction to AngularJS

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it an ideal partner with any server technology.

What is HTTP Service in AngularJS ?

AngularJS provides $http control which works as a service to read data from the server. $http is an AngularJS service for reading data from remote servers. The $http is a core AngularJS service that is used to communicate with the remote HTTP service via the browser’s XMLHttpRequest object or via JSONP.

Syntax:

$http({
method: ‘Method_Name’,
url: ‘/someUrl’
}).then(function successCallback(response) {
//when the response is available, this callback will be called asynchronously
}, function errorCallback(response) {
// this method will called when server returns response with an error status.
});

The $http service is a function that takes a configured object to generate a HTTP request and return the response. This response contains data, status code, header, configuration object and status text. In $http the first function executes on successful callback and the second function executes on error.

Lets’s begin…

(If you already familiar with JSON and mocky.io you can skip this part as well…)

In this example let’s make a simple frontend to get data from the backend of our website. In this example, I will use mocky.io platform to make a fake back end. Here, I need to store some data in our backend for later use in my application. Just follow the below steps to store some data in the backend.

Step 1 : Create some data in JSON format. ( here I will use JSON, but you can also use any other standard for this step.)

[{"username": "Lakshitha","age": 22,"hometown": "Galle"},{"username": "Gamsun","age": 23,"hometown": "Walasmulla"}]

Step 2 : For a better manner try to verify your data using a validator before apply it in mocky.io. Here I used a JSON validator (jsonlint.com) to verifying my data is in the correct JSON format.

Step 3 : Go to mocky.io, and make a new mock. paste your JSON (or any other format) data into HTTP Response Body and generate a link.( make sure Response-Content-Type is in the correct format you use.) after that copy your generated link for later use.

here’s my link : https://run.mocky.io/v3/dab08818-cc12-4ca0-9935-1313ce2a2864

Let's begin works with AngularJS

First, you need to create ng-app and register the controller for ng-app in our AngularJS application and inject $http and $log services into our app. to do that, you need to follow the below steps,

Step 1: Open a new text document and make a code as below.

var myApp = angular.module("myApp", []);var myController = myApp.controller("myController", function ($scope, $http, $log) {$http({method: 'GET',url: 'https://run.mocky.io/v3/dab08818-cc12-4ca0-9935-1313ce2a2864',headers: { 'Content-type': 'application/json' }}).then(function (response) {$scope.userdata = response.data;$scope.status = response.status;$log.info(response);}, function (reason) {$scope.error = reason.data;alert("Unsuccesfull call...");});});

You can also create this without making variables. As below,

angular.module("myApp", []).controller("myController", function ($scope, $http, $log) {$http({method: 'GET',url: 'https://run.mocky.io/v3/dab08818-cc12-4ca0-9935-1313ce2a2864',headers: { 'Content-type': 'application/json' }}).then(function (response) {}).then(function (response) {$scope.userdata = response.data;$scope.status = response.status;$log.info(response);}, function (reason) {$scope.error = reason.data;alert("Unsuccesfull call...");});});

Both methods are the same.

Code for http_example.js

Explanation : In the $http function, I have used “GET” method because I need to get data from my database. here I used my generated URL from mocky.io. because it’s work as a site backend. after here in .then function, you can see two functions. The first one is executing when the response to my request was successful. In this function, I was assigned data of response to the userdata scope. The second function is the caller error callback function. this one is executed when the error has happened in my request.

Step 2 : Save this file as a Javascript file.(with .js extension) for Example http_example.js

Step 3 : After that, we are done with half of our process. we were got data from the database through the above steps. Next, we need to show this data using our frontend to a client.

To make this, you need to create HTML file with a table to show the data we got from our backend. Create a HTML file with the following code,

<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="http_example.js"></script>
</head>
<body ng-controller="myCon">
<div>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Hometown</th>
</tr>
<tr ng-repeat="user in userdata">
<td>{{user.username}}</td>
<td>{{user.age}}</td>
<td>{{user.hometown}}</td>
</tr>
Code for index.html

Note : In the HTML head, you need to import your AngularJS CDN and your http_example.js file as well.

Explanation : in the HTML table, I have created three columns as Name, Age and Hometown to display the data to the client. In here, I had got this data as an Array. because of that to display them, I need to use the ng-repeat directive in AngularJS.

Step 4 : After that save it as a HTML file. (in this example, I was saved it as index.html) Now you can open index.html in your browser and see the output as below. There is the data I got from the backend of my website.

Output

In this example, I was using the HTTP service in AngularJS for the GET the data from a database. You can also use the POST method and Post clients data to your database as well. I will see you next time with my Next blog on How to make a POST method using AngularJS HTTP Service.

--

--