如何循环 .subscribe observable [英] How to loop .subscribe observable

查看:46
本文介绍了如何循环 .subscribe observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试创建一个循环的函数,并通过使用 .subscribe 我每次都获得一个数组对象,以便稍后我可以将数据推送到另一个数组中.循环有效,但问题是结果不是我想要的,因为 .subscribe 部分正在打印第一个数组,然后它给我空数组,而它假设打印 20x 相同的数组.我目前开始尝试使用 angular,根据我对其他语言的了解,我认为首先打印Test"x20 并在进入订阅和打印之后效果不佳.

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.

功能:

testingFunction()
{
   let i: number = 0;

   while(i < 20){

   console.log("Test");

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

    i++;
  }
}

推荐答案

由于您使用的是 Angular,因此您可以使用 RxJS 运算符来处理这种情况.forkJoin 运算符将允许您等待 while 循环操作在返回所有 observable 之前完成.

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

这篇关于如何循环 .subscribe observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆