Inquiry about angular promises

1

Good, my doubt is this, I am trying to get the data from a api that is in url , I use $http.get , I assign it to $scope.ips and it shows me the data in console.log() respective, now the problem is that $http.get is a promise so it returns the data once they are available, but since I would like to do the following print the data out of $http.get , as I could do, then I try to do it and I get the empty object, I know it is a simple example, but I have been in other projects to consult data of api , and from the data of that api , consult again data in it 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 would like to do something else within the same query, so on as you see the size of the code increasing as you could 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);


})
    
asked by Kevin AB 23.11.2016 в 02:56
source

1 answer

1

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 of the first request, I cast another request and return the promise ($ http.get ()) so that the next 'then' can be chained to the second request.

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)
   .then(function(res){
     $scope.ips=res.data;
     console.log($scope.ips.isp) //wikimedia foundation
     //var url2="XXXXXXXXXXXXXXXXX"+data.city;
     var url2 = "http://ip-api.com/json/8.8.8.8"; //otro link de ejemplo pero aquí ya puedes usar la información del primer request.
     return $http.get(url2); // otro request
  }).then(function(resFromUrl2) { // información que proviene de otro request
    console.log(resFromUrl2.data.isp); // google.
  }); // podrías agregar mas promesas encadenadas con las respuestas anteriores.
});

I'll give you the complete example in codepen

    
answered by 23.11.2016 / 04:26
source