ここでは、外部APIへのRESTful呼び出しをしようとしています。 1回の呼び出しで2つのことを達成しようとしています。したがって、2つの入れ子関数を持つ1つの関数があります。 最初に検索APIを呼び出して商品を検索します。 2番目のAPIは、推奨APIを呼び出して、最初のAPIの結果に基づいて推奨事項を取得します。角度からの快適な呼び出しが結果を返さない
私のAngularJSコードは以下の通りです。
var walmartAssn= angular.module('myApp', ['ngResource']);
walmartAssn.controller('walmartAssnController', function($scope,$resource) {
//define the API urls
var urlSearchProductApi= 'http://api.walmartlabs.com/v1/search';
var urlRecProductApi='http://api.walmartlabs.com/v1/nbp';
//define API key
var keyApi='exampleKey123';
$scope.searchProductMethod= function(){
//pass the value from the user input text box
$scope.searchItem = $scope.item ;
$scope.productId;
//get the data from the Walmart product search API
searchRequest = $resource(urlSearchProductApi, { callback:
"JSON_CALLBACK" }, { get: { method: "JSONP" }});
//pass the input text as a parameter through a GET request
$scope.searchedProducts = searchRequest.get({ apiKey: keyApi,
query: $scope.searchItem });
console.log($scope.searchedProducts.$promise);
$scope.searchedProducts.$promise.then(function(eventDetail){
//fetch the ID of the first item
$scope.productId = eventDetail.items[0].itemId;
});
recommendRequest = $resource(urlRecProductApi, { callback:
"JSON_CALLBACK" }, { get: { method: "JSONP" , isArray:true}});
console.log(recommendRequest);
$scope.recommendedProducts = recommendRequest.get({ apiKey:
keyApi, itemId: 42608121 });
console.log($scope.recommendedProducts)
$scope.recommendedProducts.$promise.then(function(){
$scope.recommendedProductsList = eventDetail;
console.log("Print recommended list");
console.log(eventDetail);
console.log($scope.recommendedProductsList);
console.log('End');
});
} });
上記のアプリケーションでは、最初の関数は2番目の関数が返さない結果を返します。
クロムコンソールで次のようなことが起こっていますが、第2の機能がブロックされている間は、fist関数はJSONの配列を返しません。
クロムコンソールの[ネットワーク]タブで、私は以下の通りのように呼び出しが成功した見ながら。
また、私は、ブラウザ内のハードコードされた値にURLを試してみましたし、正常に働いていました。
ご協力いただきありがとうございます。
最初のリクエストの結果に依存するコードはすべて、その約束の部分から入ってくるか、呼び出されなければなりません。 –
ありがとうマイク、それは正しかったかどうかは分かりません。 '$ scope.searchedProducts $ promise.then(関数(eventDetail){ $ scope.productId = eventDetail.items [0] .itemIdと、 }。.then(関数(){ $スコープ。recommendedProducts = recommendRequest.get({apiKey:keyApi、itemId:42608121}); console.log($ scope.recommendedProducts); $ scope.recommendedProductsList = eventDetail; } )); ' –