-1

I have a question i want to loop through an .subscribe() method which is in an ngOnInit() method:

 ngOnInit() {
    this.service.getEmployees().subscribe(
      (listBooks) => {
         this.books = listBooks
        var events: CalendarEvent[] = [
        {
          start: new Date(this.books[0].date_from_og), //loop instead of 0
          end: new Date(this.books[0].date_to_og),
          title: "" + this.books[0].device + "", 
          color: colors.yellow,
          actions: this.actions,
          resizable: {
          beforeStart: true,
          afterEnd: true
         },
         draggable: true
        }];
        this.events = events;
      },
      (err) => console.log(err)
    ); 

  }

I want to loop through the books[ ] Array and push every item in the events[ ] Array but I don't know how

2 Answers2

1

Then, you can just iterate over the books array instead:

ngOnInit() {
  this.service
    .getEmployees()
    .subscribe(
    (listBooks) => {
      this.books = listBooks;
      this.events = this.books.map((book) => {
        return {
          start: new Date(book.date_from_og), // use the book (current element in the iteration) directly here
          end: new Date(book.date_to_og),
          title: "" + book.device + "", 
          color: colors.yellow,
          actions: this.actions,
          resizable: {
            beforeStart: true,
            afterEnd: true
          },
          draggable: true
        };
      });
    },
    (err) => console.log(err)
  ); 
}
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
0

Try this:

this.books.forEach(element => {
  let event = {
    start: new Date(element.date_from_og),
    end: new Date(element.date_to_og),
    title: "" + element.device + "",
    color: colors.yellow,
    actions: this.actions,
    resizable: {
      beforeStart: true,
      afterEnd: true
    }
  }
  this.events.push(event)
});
Rohit Sharma
  • 3,304
  • 2
  • 19
  • 34
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79