2016-07-22 9 views
2

私はJavascriptでHTTPリクエストを作成し、このリクエストの結果を取得する関数を作成しようとします。Angular JSのHTTPリクエストの値を返す

$scope.getInfo = function() { 
     return $http({ 
      method: 'GET', 
      url: 'https://api.net' 
     }).then(function (response) { 
      return response.data; 
     }); 
    }; 

そして、他の1:残念ながら、私は絶対に

は(両方が同じことを行う必要があります)ここに私の機能の両方を検索..他の機能に戻って、この結果を取得する方法がわかりません:

$scope.getInfo = function() { 
     var defer = $q.defer(); 
     $http.get('https://api.net').then(function(response) { 
      defer.resolve(response.data); 
     }, function(response) { 
      defer.reject(response); 
     }); 
     return defer.promise; 
    }; 

私は「要求を作るための方法に関する多くの記事が見つかりましたが、その値(他の1関数の簡単な呼び出しを取り戻すためだけではなく、「対象オブジェクト」を表示し、私はdidnのしています正しく表示するための解決策を見つける)。

$scope.test = function() { 
     var myValue = $scope.getInfo(); 
     alert(myValue); /* show [Object object] */ 
    }; 

お願いします。

答えて

1

約束使用するときは、次のように進めるべき:

$http({ 
    method: 'GET', 
    url: 'https://api.net' 
}).then(function (response) { 
    $scope.info = response.data 
}); 

あなたの現在のコードリターンの約束をあなたはGETINFOになりたい場合はGETINFOによって返された結果が、オブジェクト

と考えられている理由です、あなたはこのように行うことができます機能:

$scope.getInfo = function() { 
    return $http({ 
     method: 'GET', 
     url: 'https://api.net' 
    }).then(function (response) { 
     return response.data; 
    }); 
}; 

$scope.getInfo().then(function(result) { 
    alert(result); 
}); 
1

$httpサービスを使用する際の一般的な間違いは、このSERVの戻り値を代入することですあなたが望むものではない約束である変数への氷の方法。

$scope.getInfo = function() { 
     return $http({ 
      method: 'GET', 
      url: 'https://api.net' 
     }).then(function (response) { 
      return response.data; 
     }).catch(function(error){ 
      // do something with error 
      throw error; 
     }); 
    }; 

getInfoを約束して、必要なデータ値に解決されます将来的にはその約束を返すメソッドです。

は、以下のコードを検討してください。

あなたのコントローラでこのようにそれを使用する場合:

myValue

$scope.test = function() { 
     var myValue = $scope.getInfo(); 
     alert(myValue); /* show [Object object] */ 
    }; 

値は約束(あなたは、単にconsole.log(myValue)を行うことができます)、提案の方法は、以下のようにこの方法を使用することです

$scope.test = function() { 
     $scope.getInfo() 
      .then(function(response){ 
       var myValue = response.data; 
       alert(myValue); /* show [Object object] */ 
      }).catch(function(error) { 
       console.log(error); 
       throw error; 
      }) 

    }; 
関連する問題