具有array.push()的无限循环在角中

问题描述 投票:0回答:1

我有一个小问题,我不明白为什么...

情况:我当天有很多预订。我想,如果我点击“晚上”按钮,则只保留晚上的预订。

当单击按钮时,在父组件中调用getEvening()函数。

在我的子component.html中,我有:

<tbody *ngFor="let resa of resas">
        <tr class="addred" (click)='setResa(resa)'>
            <td *ngIf="!size">{{ resa.confirmResa }}</td>
            <td>{{ resa.arrivee.split(' ')[1] }}</td>
            <td>{{ resa.nom_client }}</td>
            <td *ngIf="!size">{{ resa.nbre_client }}</td>
            <td *ngIf="!size">{{ resa.num_phone_client }}</td>
            <td *ngIf="!size">{{ resa.num_table }}</td>
            <td *ngIf="!size">{{ resa.formule }}</td>
            <td *ngIf="!size" (click)="stopEvent($event)" (mouseover)=setResaId(resa)>

                <input class="venu" type="checkbox" clrToggle (change)="came($event)" [checked]="resa.venu === 1" />
            </td>
        </tr>
    </tbody>

在我的子component.ts中,我有:

export class ReservationTabComponent implements OnInit {


  @Input() date: Subject<string>;

  @Output() resa = new EventEmitter<any>();

  addred: boolean;
  resas: any[] = [];
  resaId: string;

  dateDay: string;
  hour: number;

  scrHeight: number;
  scrWidth: number;

  size: boolean;
  bool: boolean;

  venu: number;

  constructor(
    private datastore: DatastoreService,
    private resaService: ReservationService
  ) { }

  ngOnInit(): void {
    this.getScreenSize();
    this.date.subscribe((date) => {
      this.dateDay = date;
      this.setDate(this.dateDay);
    });
    this.addred = false;
  }

  setDate(date: string) {
    this.datastore.findResaOfTheDay(date)
      .subscribe(
        (resas) => {
          this.resas = resas.data.original;
          console.log(this.resas);
        });
  }



  getAll() {

    this.setDate(this.dateDay);
  }

  getMidi() {
    this.resas = [];
  }

  getEvening() {
    for (let resa of this.resas) {

      this.hour = parseInt(moment().format(resa.arrivee.split(' ')[1]), 10);
      if (this.hour > 13) {
        this.resas.push(resa);  <-- this causing infinite loop...
        console.log(resa);  <-- this works correctly
      }
    }
  }
}

实际上,当我单击按钮时,我使用push()方法而不是console.log()方法有无限循环...

我不明白为什么...

arrays angular typescript push infinite-loop
1个回答
1
投票

您将更多元素推到要迭代的同一列表中,因此,每次推入元素时,都将对其进行迭代,然后再次推入并永久重复。

假设您匹配B:

 v 
[A,B,C]

   v 
[A,B,C] push B

     v 
[A,B,C,B]

       v 
[A,B,C,B] push B

         v 
[A,B,C,B,B] push B

           v 
[A,B,C,B,B,B] push B

您可能要使用两个不同的数组:)

© www.soinside.com 2019 - 2024. All rights reserved.