Jose Peres
Jose Peres

Reputation: 317

Call $http inside AngularJS function

I've been trying for a while to get the data from this call, but it always returns "undefined"

httpCall = function(sTformName) {
  let sURL = "https://urlthisone/api/",
  response; 

  $http.get(sURL)
    .success(function(data) {
      response = data;
    });
}

Any ideas on what I'm doing wrong? Thanks in advance.

Upvotes: 1

Views: 289

Answers (3)

dsych
dsych

Reputation: 762

Please, see documentation - https://docs.angularjs.org/api/ng/service/$http#get

According to it, if you use angular.js 1.4.3+, $http.get(sURL) returns promise. So you need $http.get(sURL).then(...) Also, see $http.get(...).success is not a function might will help

Upvotes: 0

nixkuroi
nixkuroi

Reputation: 2269

You're making an async call, and it will not return a value. It calls success and inside success you need to use a callback method in order to get the value you want, and work with it.

function doSomethingWithTheData(data) {
  // process the data here.
}

httpCall = function(sTformName, callback) {
    let sURL = "https://urlthisone/api/",
    response; 

    $http.get(sURL)
        .success(function(data) {
        callback(data); // here's where we call the callback
    });
}

// call it with the callback
httpCall(fornName, doSomethingWithTheData);

Upvotes: 0

scniro
scniro

Reputation: 16989

You can return and resolve the promise...

httpCall = function(sTformName) {
  let sURL = 'https://urlthisone/api/',
  return $http.get(sURL);
}

httpCall('myForm').then(response => {
  console.log(response.data);
});

$http.get is an asynchronous call and must be handled accordingly, in this case, by resolving the returned Promise

Upvotes: 3

Related Questions