$http is an important service in
AngularJS which helps in making Ajax calls to the server, $http takes the service URL to be
invoked as a parameter, makes calls to the server gets the response and service
and passes it back to Angular
The syntax for making Ajax calls using $http is as follows
$http.get('serviceURL').
success(function(data, status, headers, config) {
// Process response for Success here
}).
error(function(data, status, headers, config) {
// Process response for Failure here
});
$http supports Get, Post and Delete operations, all these take the service URL as parameters, the Post variant in addition takes the Post data which is to be submitted to the service.
The following example shows how to make an API call using $http and display the results in the view using ng-repeat directive.
<html ng-app>
<head>
<meta charset="utf-8" />
<title>AngularJS - Basic</title>
<script src="angular.min.js"></script>
<script>
function httpAjaxController($scope,$http){
$scope.Title = "Package List";
$http.get("http://localhost:7630/api/Package")
.then(function (results) {
//Success;
try {
$scope.packageList = results.data;
}
catch (err) {
alert(err.message);
}
}, function (results) {
//error
alert("Error: " + results.data + "; "
+ results.status);
})
}
</script>
</head>
<body>
<div ng-controller="httpAjaxController">
<b>{{Title}}</b><br/>
<ul>
<li ng-repeat="package in packageList">
{{ package.PackageId }} - {{ package.Name }}<br/>
</li>
</ul>
</div>
</body>
</html>
The syntax for making Ajax calls using $http is as follows
$http.get('serviceURL').
success(function(data, status, headers, config) {
// Process response for Success here
}).
error(function(data, status, headers, config) {
// Process response for Failure here
});
$http supports Get, Post and Delete operations, all these take the service URL as parameters, the Post variant in addition takes the Post data which is to be submitted to the service.
The following example shows how to make an API call using $http and display the results in the view using ng-repeat directive.
<html ng-app>
<head>
<meta charset="utf-8" />
<title>AngularJS - Basic</title>
<script src="angular.min.js"></script>
<script>
function httpAjaxController($scope,$http){
$scope.Title = "Package List";
$http.get("http://localhost:7630/api/Package")
.then(function (results) {
//Success;
try {
$scope.packageList = results.data;
}
catch (err) {
alert(err.message);
}
}, function (results) {
//error
alert("Error: " + results.data + "; "
+ results.status);
})
}
</script>
</head>
<body>
<div ng-controller="httpAjaxController">
<b>{{Title}}</b><br/>
<ul>
<li ng-repeat="package in packageList">
{{ package.PackageId }} - {{ package.Name }}<br/>
</li>
</ul>
</div>
</body>
</html>
No comments:
Post a Comment