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

Posted

技术标签:

【中文标题】如何在订阅和 ngOnInit 方法中循环遍历数组?【英文标题】:How to loop through an Array in a subscribe and ngOnInit method? 【发布时间】:2019-10-06 18:44:54 【问题描述】:

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

【问题讨论】:

【参考方案1】:

试试这个:

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

【讨论】:

【参考方案2】:

然后,您可以只遍历 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)
  ); 

【讨论】:

以上是关于如何在订阅和 ngOnInit 方法中循环遍历数组?的主要内容,如果未能解决你的问题,请参考以下文章

订阅角度时无法在 ngoninit 中获得价值

组件 ngOnInit 中的 Angular 订阅

Angular订阅推送对象到数组

组件销毁并重新访问后,订阅在 ngOnInit 函数中运行

Angular ngOnInit 如何将订阅结果用于另一个订阅/后端调用?

如何以角度循环遍历异步数据