2017-05-17 10 views
1

私は論理的な問題があります。Angular JSの連鎖約束の問題

私はlocalStorageにオブジェクトの配列を持っています。私がしたいのは、それぞれが効果的にAPI呼び出しを行い、localStorageに新しいアイテムをプッシュし、すべてが完了したらroute to a new componentだけです。

if(migrationName){ 

     angular.forEach(JSON.parse($window.localStorage.selectedItems), function(item) { 
      var url = '/api/get_all_prices/'+item.details.id+'/us-1'; 
      HttpWrapper.send(url,{"operation":'GET'}).then(function(pricingOptions){ 
       item.selectedMapping = pricingOptions[0]; 
       vm.selectedItems[type].push(item); // Store it in a variable first  
       $window.localStorage.setItem('selectedItems',JSON.stringify(item)); 
      }); 

     }); 
     $rootRouter.navigate(["MigrationRecommendation"]); // Route once everything is done 
} 

私はこれが間違っていることを知っています。

私はループのたびにlocalStorageを設定していますが、配列内のすべてが実行された後は処理ができません。

ロジックはどのように変更できますか?

答えて

2

あなたはArray.prototype.mapで作成した約束の配列で$ q.allを使用する必要があります。

var items = JSON.parse($window.localStorage.selectedItems) 

var promises = items.map(function(item) { 
    var url = '/api/get_all_prices/' + item.details.id + '/us-1'; 
    return HttpWrapper.send(url, {"operation": 'GET'}).then(function(pricingOptions) { 
    item.selectedMapping = pricingOptions[0]; 
    vm.selectedItems[type].push(item); // Store it in a variable first  
    $window.localStorage.setItem('selectedItems', JSON.stringify(item)); 
    }); 
}); 

$q.all(promises).then(function() { 
    $rootRouter.navigate(["MigrationRecommendation"]);  
}) 
+0

ええ、あなたが正しいと迅速でした。 :) –

+0

@ dfsq答えに感謝します。しかし、毎回localStorageを変更するのではなく、すべての項目をまとめてlocalStorageに追加してはいけません。あなたは私が推測するアイテムのためにそれをやっているのですが、それは選択されたすべてのアイテムに対して実行されるべきです。 – StrugglingCoder