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

Angular: How to use a service in a for loop?

如何在 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() 函数。

提前致谢

你需要使用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(); });

那你或许可以找到更优雅的方式。