Answer code you mentioned as reference:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script>
angular.module('app', []);
angular.module('app').controller('MyCtrl', function MyCtrl($http, $scope){
$scope.busca = function(){
$http.get('http://api.postmon.com.br/cep/'+ $scope.cep).success(function(local){
$scope.local_encontrado = local;
console.log(local);
});
};
$scope.enter = function(e){
if(e.keyCode == 13){
$scope.busca();
};
};
});
</script>
Note that the example uses only the method success
, that is, when no error returns and the response status is 2**
, usually 200
. So what’s missing? Another method called error
, intended to treat when a certain error occurs, such as the one you mentioned, see how the code looks:
Code change handling errors:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>
<script>
angular.module('app', []);
angular.module('app').controller('MyCtrl', function MyCtrl($http, $scope){
$scope.busca = function(){
$http.get('http://api.postmon.com.br/cep/'+ $scope.cep)
.success(function(local){
$scope.local_encontrado = local;
console.log(local);
})
.error(function(e) {
alert("Erro ao carregar CEP");
});
};
$scope.enter = function(e){
if(e.keyCode == 13){
$scope.busca();
};
};
});
</script>
In the body of the code I entered the function error
so that when a certain error occurs show an Alert for the user to know what happened, it will usually be called this method when a status of an HTTP response is 4**
or 5**
.
This will treat the errors as the error you mentioned, but if you don’t find a particular zip code refer to the API documentation you’re using to verify your return. Even not finding the zip code, will fall inside success
to treat this information, will not fall within error
because it was a successful requisition, right?
References:
http://tutorials.jenkov.com/angularjs/ajax.html
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Are you asking for the zip code via js? or are you using php or another method? can show the code that makes the call?
– celsomtrindade
Could provide the angular code snippet containing the query?
– Ricardo Rodrigues de Faria
Can you edit with your code? I will make a reply using the example of the guy how it can be done.
– Giancarlo Abel Giulian