首页 > 解决方案 > 如何在订阅和 ngOnInit 方法中循环遍历数组?

问题描述

我有一个问题,我想遍历 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[] 数组中的每个项目,但我不知道如何

标签: angulartypescriptloopssubscribengoninit

解决方案


然后,您可以只迭代 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)
  ); 
}

推荐阅读