Good, my doubt is the following, I am trying to obtain the data
from one api
that is in url
, I use $http.get
, I assign it to $scope.ips
and it shows me the data in the console.log()
respective one, now the problem is that it $http.get
is a promise so it returns the data once they are available, but given that I would like to do the following print the data outside the $http.get
, how could I do it, because I try to do it and I get the empty object, I know it is a simple example, but in other projects I have had to consult data from a api
, and from of the data in that api
, query data in it again forming an endless spaghetti code.
var app=angular.module("app",[]);
app.controller("main",function($scope,$http){
$scope.ips={};
var url="http://ip-api.com/json/208.80.152.201";
$http.get(url)
.success(function(data){
$scope.ips=data;
console.log($scope.ips)
});
console.log($scope.ips);
})
For example, if you wanted to do something, another query within the same query, so on, as you see, the size of the code increases, how could you modularize it.
var app=angular.module("app",[]);
app.controller("main",function($scope,$http){
$scope.ips={};
var url="http://ip-api.com/json/208.80.152.201";
$http.get(url)
.success(function(data){
$scope.ips=data;
console.log($scope.ips)
var url2="XXXXXXXXXXXXXXXXX"+data.city;
$http.get(url2)
...
....
});
console.log($scope.ips);
})
What I understand is that you need to execute more actions after receiving certain asynchronous responses and effectively, as you say, if you execute the chained code, you will end up with a Callback Hell , for this the promises are used. I show you an example of how you can chain your promises so that your code does not have too much indentation.
Following your code after receiving the response from the first request, I launch another request and return the promise ($http.get()) so that the next 'then' can be chained with the second request.
I leave you the complete example in codepen