1

I have a logical issue.

I have an array of objects in localStorage. What I want to do is , for each of them effectively make an API call and then push the new item in localStorage and once everything is done then only 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
}

I know this is wrong.

I am setting localStorage each time in the loop and also I am not handling once everything in the array is done then only route.

How can the logic be changed ?

1 Answer 1

2

You should use $q.all with array of promises created with Array.prototype.map:

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"]);    
})
Sign up to request clarification or add additional context in comments.

1 Comment

@dfsq Thanks for the answer. But instead of modifying localStorage each time should not we just add all the items together and then append to localStorage. You are doing it for only a item I guess instead it should be done for all the selected items.

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.