2

I am trying to obtain data from getAllDatas method.

This works fine without any error:

var getAlldatas = function ($http) {
    var getuser = function (username) {
        return $http.get("https://api.github.com/users/" + username).then(function (response) {
            return response.data;
        });
    };

This throws error:

 var getAlldatas = function ($http) {
     var getuser = function (username) {
         var pro = $http.get("https://api.github.com/users/" + username).then(getThis);

         var getThis = function (response) {
             return response.data;
         };

         return pro;
     };

How ever i get the following error message for the second one

angular.js:10071 TypeError: Cannot read property 'protocol' of undefined

How is the second one different from first and why does this throw error?
Why don't both behave in a similar way?

1
  • 4
    In the second example the var pro = ... line is actually var pro = $http.get("https://api.github.com/users/" + username).then(undefined); -> Hoisting Commented Nov 4, 2017 at 11:42

3 Answers 3

4

It's how JavaScript works. Function declarations are hoisted to the top of the code page while initializations aren't.

Reference--Thanks to @Andreas

You are defining getThis after you are using it.

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

1 Comment

Function declarations are hoisted.
2

Your second definition breaks into

 var getuser = function (username) {
    var pro, getThis;
    pro = $http.get("https://api.github.com/users/" + username).then(getThis);
    getThis = function (response) {
        return response.data;
    };
    return pro;
};

And getThis is just undefined during assigning a value to the pro variable. This issue occurs due to immediate .then call and taking it's callback argument which is undefined in work. The next code fixes the problem:

 var getuser = function (username) {
    var pro = $http.get("https://api.github.com/users/" + username)
              .then(function(result) { getThis(result); });
    var getThis = function (response) {
        return response.data;
    };
    return pro;
};

In this case the callback argument is not undefined and it will pass to the AngularJS properly, and getThis variable will have time to get it's value.

Comments

1

use like this:

  var getuser = function (username) {
  var pro = $http.get("https://api.github.com/users/" + username)
          .then(function(getdata) { getThis(getdata); });
  var getThis = function (response) {
    return response.data;
  };
  return pro;
  };

Comments

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.