如何在订阅和 ngOnInit 方法中循环遍历数组?

How to loop through an Array in a subscribe and ngOnInit method?

我有一个问题想遍历 ngOnInit() 方法中的 .subscribe() 方法:

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

  }

我想遍历 books[ ] 数组并推送 events[ ] 数组中的每个项目,但我不知道如何

然后,您可以直接遍历 books 数组:

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

试试这个:

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