Austin Truex Austin Truex - 1 month ago 5
Javascript Question

Passing variable between functions in a service in angularjs

I have been searching for an answer to this, and cannot seem to find anything. I have a service, in the first block I am successfully logging a url that I then need to pass into my

getData()
function. But it comes back undefined, I have tried the method below, and I tried moving the first
$http.get
into the controller where I am calling it, as well as moving the first $http.get into the
getData()
function. Am I going about this all wrong?

di.service('testService', function($http) {
$http.get('https://us.api.data/tichondrius?locale=en_US&apikey=xxxxxxxx').
then(function(response) {
var urlToJsonFileUncut = response.data.files[0].url;
console.log(urlToJsonFileUncut);
urlToJsonFile = urlToJsonFileUncut.slice(7);
console.log(urlToJsonFile);
return urlToJsonFile;
});
this.getData = function(urlToJsonFile) {
console.log(urlToJsonFile);
return $http.get('http://localhost:1337/' + urlToJsonFile).
then(function(response) {
console.log(response.data.realms[0].name);
return response.data.realms[0].name;
});
}});

Answer

$http is an async request. so you need to chain it inside the first request to ensure the value of first response is available when second request is called.

di.service('testService', function($http) {
  var getData = function () {
    return $http.get('https://us.api.data/tichondrius?locale=en_US&apikey=xxxxxxxx').
    then(function(response) {
      var urlToJsonFileUncut = response.data.files[0].url;
      console.log(urlToJsonFileUncut);
      var urlToJsonFile = urlToJsonFileUncut.slice(7);
      console.log(urlToJsonFile);

      $http.get('http://localhost:1337/' + urlToJsonFile).
      then(function(response) {
        console.log(response.data.realms[0].name);
        return response.data.realms[0].name;
      });
    });
  }

  return { getData: getData; }
});