1

I have an array of objects I declared in my controller like this

vm.reviews = [];

Next, I have a function that calls a service to load all the objects from the database declared like this

vm.loadAllReviews = loadAllReviews;
function loadAllReviews() {
        Review.query({

        }, onSuccess, onError);
        function onSuccess(data) {
            vm.reviews = data;
            console.log(vm.reviews.length);  //Shows 7
        }
        function onError(error) {
            AlertService.error(error.data.message);
        }
    }

I want to iterate through the reviews in another functions, but, after calling loadAllReviews in that functions, it shows that vm.reviews' length is actually 0 and, as such, cannot be used. The function looks like this

function testLocatii() {
        loadAllReviews();
        console.log(vm.reviews.length); //Shows 0
        for (var i = 0; i<vm.reviews.length;i++) {
            console.log("suntem in for");
            vm.locations.push(vm.reviews[i].coordonateLocatie);
        }
    }

Why is all of the sudden the vm.reviews array empty? I'd also like to point out that if I try to display the content of the vm.reviews array in page and use ng-repeat in HTML, it works perfectly. So why is it empty when I try to use it in that function?

P.S. I mention that I do not do any other sort of operation(slice, sort or what not) on vm.reviews

Ginel Guiu
  • 39
  • 4
  • Because `Review.query()` is asynchronous. So, you're looping through `vm.reviews` before it's been populated by the `onSuccess` callback. – Guillaume Georges Jul 13 '18 at 15:43

0 Answers0