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

时间:2018-08-01 09:20:45

标签: angular loops angular-services

如何在for循环中使用服务,并在所有循环执行完服务后进一步编写代码?我的代码如下:

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

当所有日历的所有约会都推送到数组时,我需要启动getCalendarDisplay()函数。

预先感谢

1 个答案:

答案 0 :(得分:1)

您需要使用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>

在您的情况下,您需要执行以下操作:

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

然后您可能会找到更优雅的方式。