Here we will learn how to use angularjs success and error functions with then property in http service with example.
In angularjs while using $http services we have success() and error() functions with then property to display the success and failed response of request information. In angularjs we can use success and error methods with http GET, POST, PUT, DELETE, JSONP and PATCH services.
Following is the syntax of using success and error functions with $http.get method.
var app = angular.module('getserviceApp', []);
app.controller('getserviceCtrl', function ($scope, $http) {
// Simple GET request example:
$http.get("url").then(function success(response) {
// this function will be called when the request is success
}, function error(response) {
// this function will be called when the request returned error status
});
});
If you observe above syntax we defined two functions in then method with $http.get service. Here first function is used to handle success response and second function is used handle error response. Same way we can use success and error functions other services $http.post, $http.put, $http.delete and $http.jsonp.
We will see simple example to use success and error functions in angularjs $http.get service.
Following is the example of using success and error functions with $http.get service in angularjs application.
<!DOCTYPE html>
<html>
<head>
<title>
AngularJs $http.Get() Service with Success / Error Response Example
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('getserviceApp', []);
app.controller('getserviceCtrl', function ($scope, $http) {
// Simple GET request example:
$http.get("sample1.html").then(function success(response) {
$scope.myWelcome = response.data;
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
}, function error(response) {
$scope.myWelcome = "Service Not Exists";
$scope.statusval = response.status;
$scope.statustext = response.statusText;
$scope.headers = response.headers();
});
});
</script>
</head>
<body>
<div ng-app="getserviceApp" ng-controller="getserviceCtrl">
<p>Hi, Guest</p>
<h1>{{myWelcome}}</h1>
<p>StatusCode: {{statusval}}</p>
<p>Status: {{statustext}}</p>
<p>Response Headers: {{headers}}</p>
</div>
</body>
</html>
Now we will run and see the output of above angularjs applications.
Following is the result of our angularjs application with success and error functions.
If you observe above output we got error because we mentioned url “sample.html” in $http.get service but that file not exists in our application.
Now create new html file in your application and give name as ‘sample.html’ and open that html file and remove complete default code and write the code like as shown below
Now we will run and see the output of angularjs $http.get service application that would be like as shown below.