Sebastian S
Sebastian S

Reputation: 397

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? 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.

Thanks in advance

Upvotes: 0

Views: 794

Answers (1)

AnTiToinE
AnTiToinE

Reputation: 421

You need to use Observable forkJoin, look at this example:

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>

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.

Upvotes: 1

Related Questions