1

I want to use the variables from two http requests. I tried to use rootScope, but it doesn't work. dlon and dlat are still undefined. Here is the code.

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope,$rootScope, $http) {
    $http.get("http://api.zippopotam.us/us/68503")
      .then(function (response) {
        $rootScope.lon1 = response.data.places[0].longitude;
        $rootScope.lat1 = response.data.places[0].latitude;
    });
    $http.get("http://api.zippopotam.us/us/68504")
      .then(function (response) {
        $rootScope.lon2 = response.data.places[0].longitude;
        $rootScope.lat2 = response.data.places[0].latitude;
    });
    $scope.dlon = $rootScope.lon1 - $rootScope.lon2;
    $scope.dlat = $rootScope.lat1 - $rootScope.lat2;
});

Thanks.

1
  • Your scope.dlon and scope.dlat are initialized before the end of the http.get. Commented Dec 26, 2015 at 9:19

2 Answers 2

2

You will need to use a promise which will resolve after both http requests are completed. In angular this is done with $q.

Sign up to request clarification or add additional context in comments.

Comments

0

I was curious of how it the promise solution would work

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope,$rootScope, $http, $q) {
  $q.all([
    $http.get("http://api.zippopotam.us/us/68503"),
    $http.get("http://api.zippopotam.us/us/68504")
  ]).then((a) =>{
    $scope.dlon = a[0].data.places[0].longitude - a[1].data.places[0].longitude;
    $scope.dlat = a[0].data.places[0].latitude - a[1].data.places[0].latitude;
  })
});

http://codepen.io/Anthonyzou/pen/mVrxYy

2 Comments

I works good with chrome, but in safari, AngularJS just somehow does not work. I don't know why
You probably don't want to use the arrow function syntax, it's new in ES6 and not supported everywhere. Instead of (a) => {..} use function (a){...}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.