0

I'm currently trying to make a function where it loops and by using .subscribe I'm getting an array object each time so that later on I can push the data inside an another array. The loop works but the problem is that the results is not what I want because the .subscribe part is printing the first array and then for the rest it's giving me null arrays whereas it suppose to print 20x the same array. I currently started experimenting with angular and to my knowledge of other languages I don't think that it's working good by first printing "Test"x20 and after goes inside the subscribe and printing.

Function:

testingFunction()
{
   let i: number = 0;

   while(i < 20){

   console.log("Test");

   this.testService.getAll().subscribe((object: any[]) => {
      console.log(object);
   })

    i++;
  }
}

1 Answer 1

2

Since you are using Angular, you can make use of RxJS operators to handle this scenario. The forkJoin operator will allow you to wait for the while loop operation to be completed before returning all the observables.

This is how you can make use of the operator:

testingFunction() {
   let i: number = 0;
   const observablesList = []; 

   while(i < 20){
     observablesList.push(this.testService.getAll());
     i++;
   }
   forkJoin(observablesList).subscribe((response) => {
     console.log(response);
   });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Although this answer worked in grouping the arrays, I'm still having the first array visible and the others as null
@MexicoBoy in that case, what does getAll() do? I am guessing it is some other part in your codebase that is giving you an issue

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.