Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

AngularJS Http


May 08, 2021 AngularJS


Table of contents


AngularJS XMLHttpRequest

We can use AngularJS's built-in $http services communicate directly with the outside world.

$http service simply encapsulates the browser-native XMLHttpRequest object.


$http is a core service in AngularJS that reads data from remote servers.


Read the JSON file

Here are the JSON files stored on the web server:

Customers_JSON.php

{"records":[
{
"Name" : "Alfreds Futterkiste",
"City" : "Berlin",
"Country" : "Germany"
},
{
"Name" : "Berglunds snabbköp",
"City" : "Luleå",
"Country" : "Sweden"
},
{
"Name" : "Centro comercial Moctezuma",
"City" : "México D.F.",
"Country" : "Mexico"
},
{
"Name" : "Ernst Handel",
"City" : "Graz",
"Country" : "Austria"
},
{
"Name" : "FISSA Fabrica Inter. Salchichas S.A.",
"City" : "Madrid",
"Country" : "Spain"
},
{
"Name" : "Galería del gastrónomo",
"City" : "Barcelona",
"Country" : "Spain"
},
{
"Name" : "Island Trading",
"City" : "Cowes",
"Country" : "UK"
},
{
"Name" : "Königlich Essen",
"City" : "Brandenburg",
"Country" : "Germany"
},
{
"Name" : "Laughing Bacchus Wine Cellars",
"City" : "Vancouver",
"Country" : "Canada"
},
{
"Name" : "Magazzini Alimentari Riuniti",
"City" : "Bergamo",
"Country" : "Italy"
},
{
"Name" : "North/South",
"City" : "London",
"Country" : "UK"
},
{
"Name" : "Paris spécialités",
"City" : "Paris",
"Country" : "France"
},
{
"Name" : "Rattlesnake Canyon Grocery",
"City" : "Albuquerque",
"Country" : "USA"
},
{
"Name" : "Simons bistro",
"City" : "København",
"Country" : "Denmark"
},
{
"Name" : "The Big Cheese",
"City" : "Portland",
"Country" : "USA"
},
{
"Name" : "Vaffeljernet",
"City" : "Århus",
"Country" : "Denmark"
},
{
"Name" : "Wolski Zajazd",
"City" : "Warszawa",
"Country" : "Poland"
}
]}


AngularJS $http

AngularJS $http is a service for reading data on a web server.

$http.get (url) is a function used to read server data.

AngularJS instance

<div ng-app="" ng-controller="customersController">

<ul>
<li ng-repeat="x in names">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>

</div>

<script>
function customersController($scope,$http) {
$http.get("/statics/demosource/Customers_JSON.php")
.success(function(response) {$scope.names = response; });
}
</script>

Try it out . . .

App resolution:

The AngularJS app is defined by ng-app. The app is executed in slt;div.

The ng-controller instruction sets the controller object name.

The function customersController is a standard JavaScript object constructor.

The controller object has one property: $scope.names.

$http.get() read static JSON data from the web server.

The server data file is: /statics/demosource/Customers_JSON.php.

When JSON data is loaded from the service side, $scope.names becomes an array.

AngularJS Http The above code can also be used to read database data.