简体   繁体   English

Angular:如何在for循环中使用服务?

[英]Angular: How to use a service in a for loop?

How can I use a service in a for-loop and go further in code after all loops have executed the service? 在所有循环执行服务后,如何在for循环中使用服务并进一步编写代码? My code looks like that: 我的代码如下所示:

for (let i = 0; i < this.calendarList.length; i++) {
  const curCalendarId = this.calendarList[i].id;
  this.cs.getAppointmentsWithinDay(curCalendarId, this.smallCalendarDate).subscribe(result => {
    for (let j = 0; j < result.length; j++) {
      this.calendarDisplay.appointments.push(result[j]);
    }
  });
}
this.getCalendarDisplay();

I need to start the getCalendarDisplay() function when all appointments for all calendars are pushed to the array. 当所有日历的所有约会都推送到数组时,我需要启动getCalendarDisplay()函数。

Thanks in advance 提前致谢

You need to use Observable forkJoin, look at this example: 您需要使用Observable forkJoin,请看以下示例:

 var tasks = []; tasks.push(Rx.Observable.timer(1000).first()); tasks.push(Rx.Observable.timer(1000).first()); tasks.push(Rx.Observable.timer(1000).first()); tasks.push(Rx.Observable.timer(1000).first()); console.log('Wait that all tasks are done...'); Rx.Observable.forkJoin(...tasks).subscribe(results => { console.log('done', results); }); 
 <script src="https://npmcdn.com/rxjs@5.0.0-beta.7/bundles/Rx.umd.js"></script> 

In your case, you need to make something like this: 对于您的情况,您需要执行以下操作:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/map';

let tasks = [];

for (let i = 0; i < this.calendarList.length; i++) {
  const curCalendarId = this.calendarList[i].id;
  tasks.push(
    this.cs.getAppointmentsWithinDay(curCalendarId, this.smallCalendarDate).map(result => {
      for (let j = 0; j < result.length; j++) {
        this.calendarDisplay.appointments.push(result[j]);
      }
    })
  );
}

forkJoin(...tasks).subscribe(() => { this.getCalendarDisplay(); });

Then you can probably find a more elegant way. 然后,您可能可以找到更优雅的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM