1

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.

Jose Peres
  • 197
  • 1
  • 1
  • 18
  • When a JavaScript function lacks a [return statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return) it returns `undefined`. That's the way JavaScript works. – georgeawg Sep 15 '18 at 05:16
  • Was my answer below able to help you out here? Please let me know. I'd like to help you resolve this one. – scniro Sep 17 '18 at 13:05

3 Answers3

3

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

scniro
  • 16,844
  • 8
  • 62
  • 106
0

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);
nixkuroi
  • 2,259
  • 1
  • 19
  • 25
  • The `.success` method is [deprecated and removed from version 1.6](https://stackoverflow.com/questions/35329384/why-are-angularjs-http-success-error-methods-deprecated-removed-from-v1-6/35331339#35331339). – georgeawg Sep 15 '18 at 05:11
  • Also see [Why are Callbacks from Promise `.then` Methods an Anti-Pattern](https://stackoverflow.com/questions/35660881/why-are-callbacks-from-promise-then-methods-an-anti-pattern). – georgeawg Sep 15 '18 at 05:12
  • @georgeawg His initial example uses .success, so I was providing an answer that applied to his question. Please do not down vote answers that both work, and pertain directly to the question asked. – nixkuroi Sep 17 '18 at 00:28
0

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
dsych
  • 754
  • 7
  • 13