【问题标题】:How to loop .subscribe observable如何循环 .subscribe observable
【发布时间】:2020-01-25 19:28:29
【问题描述】:

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

功能:

testingFunction()
{
   let i: number = 0;

   while(i < 20){

   console.log("Test");

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

    i++;
  }
}

【问题讨论】:

    标签: angular typescript rxjs


    【解决方案1】:

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

    这是你如何使用操作符:

    testingFunction() {
       let i: number = 0;
       const observablesList = []; 
    
       while(i < 20){
         observablesList.push(this.testService.getAll());
         i++;
       }
       forkJoin(observablesList).subscribe((response) => {
         console.log(response);
       });
    }
    

    【讨论】:

    • 虽然这个答案在对数组进行分组时有效,但我仍然让第一个数组可见,其他数组为空
    • @MexicoBoy 在这种情况下,getAll() 做什么?我猜是你的代码库中的其他部分给你带来了问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 2017-04-06
    相关资源
    最近更新 更多