Almost all modern applications need to request data from external servers.
AngularJS provides a core service named $http to handle all network requests easily.
The $http service makes asynchronous HTTP requests using the browser's XMLHttpRequest object.
It can request data via GET, send data via POST, and read JSON responses seamlessly.
It utilizes Promises, making asynchronous data management very elegant.
To make a request, you call $http.get() and pass the URL of the API.
You then chain a .then() method to capture the server's response.
The actual data is stored within the response.data object!
<div ng-app="myApp" ng-controller="myCtrl">
<p>Name: {{ userData.name }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("https://jsonplaceholder.typicode.com/users/1")
.then(function(response) {
$scope.userData = response.data;
});
});
</script>
Fetching data dynamically with $http creates incredibly fast SPA experiences.
However, because the content loads after the initial page load, some basic crawlers might miss it.
Ensure your server pre-renders important keywords, or use modern Server-Side Rendering if SEO is critical.
Which built-in AngularJS service is specifically designed for making network requests to external APIs?