如何在 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/[email protected]/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(); });
然后你可能会找到一个更优雅的方式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句