How to loop .subscribe observable

倖福魔咒の 提交于 2021-02-11 12:21:04

问题


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:


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);
   });
}


来源:https://stackoverflow.com/questions/59908602/how-to-loop-subscribe-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!