Search code examples
angulartypescriptloopssubscribengoninit

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


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


Solution

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