Как перебрать массив в подписке и метод ngOnInit? - PullRequest
0 голосов
/ 20 мая 2019

У меня есть вопрос, я хочу пройтись по методу .subscribe (), который находится в методе ngOnInit ():

 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 [] и выдвинуть каждый элементв событиях [] Массив, но я не знаю, как

Ответы [ 2 ]

1 голос
/ 20 мая 2019

Затем вы можете просто перебрать массив книг вместо:

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)
  ); 
}
0 голосов
/ 20 мая 2019

Попробуйте это:

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