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.

2
  • When a JavaScript function lacks a return statement it returns undefined. That's the way JavaScript works. Commented Sep 15, 2018 at 5:16
  • Was my answer below able to help you out here? Please let me know. I'd like to help you resolve this one. Commented Sep 17, 2018 at 13:05

3 Answers 3

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

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

4 Comments

Why 'myForm'? Where does that come from?
It's just an example, since your function httpCall takes a parameter named sTformName. I'd imagine this means something to you...
Yes, sorry. This one did the trick! Hadn't been able to answer until now. Thanks!
happy to hear :)
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);

3 Comments

@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.
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

2 Comments

The .success syntax was correct up to Angular v1.4.3 - so it depends on what version you're using.
@nixkuroi The .success method should be avoided even with older versions of AngularJS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.