2017-11-04 3 views
2

getAllDatasメソッドからデータを取得しようとしています。

これは、エラーなしで正常に動作します:私は二番目の

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

ために、次のエラーメッセージが表示されますどのように、これまで

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; 
    }; 

方法である:これはエラーがスロー

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

最初のものとは異なる2番目のものと、なぜこのエラーをスローしますか?
なぜ両方が同じように動作しないのですか?

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; 
}; 

そしてgetThis

+4

'VARプロ= ...'行が、実際には 'VARプロ= $ http.get(「https://api.github.com/ (ホイット)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) – Andreas

答えて

2

あなたの2番目の定義ブレークはちょうどundefinedpro変数に値を代入中です。この問題は、即時.thenコールが発生し、コールバック引数がundefinedであるために発生します。コールバック引数がundefinedではありません。この場合、

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; 
}; 

、それが適切にAngularJSに渡す、とgetThis変数は、それが値です取得する時間を持つことになります。次のコードは、問題を修正します。

4

JavaScriptの仕組みです。初期化は行われていないが、コードページの先頭にが掲示されてに上書きされます。

Reference --Thanksは@Andreas

にあなたがそれを使用している後getThisを定義しています。

+0

関数_declarations_吊り上げられる。 – JLRishe

1

このような使用:2番目の例では

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; 
    }; 
関連する問題