AngularJS $http Service
The $http service lets AngularJS applications send and receive data from a remote server using standard HTTP requests.
What Is $http?
$http is a built-in AngularJS service for communicating with a remote server through the browser's XMLHttpRequest object or JSONP. It is injected into a controller or custom service just like any other AngularJS service.
Calling $http.get(url) immediately sends a GET request and returns a promise. You handle the response using .then(), which receives a response object once the request completes successfully.
A Basic GET Request
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$http.get("https://example.com/api/users").then(function(response) {
$scope.users = response.data;
});
});
</script>
</body>
</html>Displaying the Result
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-repeat="user in users">{{ user.name }}</li>
</ul>
</div>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$http.get("https://example.com/api/users").then(function(response) {
$scope.users = response.data;
});
});
</script>
</body>
</html>The Response Object
The object passed into .then() contains several useful properties describing the result of the request.
Handling Errors
The promise returned by $http.get() supports a second argument, or a chained .catch(), to react when the request fails.
Handling a Failed Request
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$http.get("https://example.com/api/users").then(
function(response) {
$scope.users = response.data;
},
function(error) {
$scope.errorMessage = "Could not load users.";
}
);
});
</script>
</body>
</html>Other HTTP Methods
- $http.get(url) — retrieve data
- $http.post(url, data) — send new data to the server
- $http.put(url, data) — update existing data
- $http.delete(url) — remove data
Sending Data with POST
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$http.post("https://example.com/api/users", { name: "John" }).then(function(response) {
$scope.saved = response.data;
});
});
</script>
</body>
</html>