无法推送到角度数组

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

我有一个过滤器,用于从mongoDB中获取所有数据,并返回到日期在选定范围内的表。但是,当我运行代码时,在控制台“ 无法读取未定义的属性'push'>未定义'中收到一条错误消息。

app.component.html:

<div class="search">
    <input type="text" matInput
        id = 'calander'
        ngxDaterangepickerMd
        [locale]="{ 
          cancelLabel: 'Cancel',
          applyLabel: 'Okay',
          clearLabel: 'Clear',
          format: 'YYYY/MM/DD'
        }"
        startKey="start"
        endKey="end"
        [(ngModel)]="selected"
        name="daterange"
        (ngModelChange)="doSomething($event)"/>
    <button class="ripple" type="submit" ></button>
</div>

<table>
    <tr *ngFor="let email of filter(emails)" >
        <td class="tg-0lax" id="tableText">{{ email.Sender}}</td>
        <td class="tg-0lax" id="tableText">{{ email.Sent_To}}</td>
        <td class="tg-0lax" id="tableText">{{ email.Subject}}</td>
        <td class="tg-0lax"><!--{{ email.Attachment}} --></td>
        <td class="tg-0lax"><b>{{ email.Created_On | date: 'yyyy/MM/dd'}}</b></td>
    </tr> 
</table>

app.component.ts:

export class AppComponent {

  // Define a users property to hold our user data
  emails: Array<any>;
  filteredEmails: Array<any>;

  startDate: any;
  endDate: any;

  doSomething(event){
    this.startDate = new Date(event.start);
    this.endDate = new Date(event.end);
 }

filter(emails: any[]): any[] {
  let filteredEmails = new Array()
  if(this.startDate == null && this.endDate == null){
    this.filteredEmails = this.emails;
    return filteredEmails;
  }
  else{
    this.filteredEmails.push(emails =>
      emails.Created_On >= this.startDate && emails.Created_On <= this.endDate);
  }

  return filteredEmails;
}

constructor(private _dataService: DataService) {

    // Access the Data Service's getUsers() method we defined
   this._dataService.getEmails()
        .subscribe(res => this.emails = res);
    }
}
angular mean-stack angular-filters
1个回答
0
投票

您在调用this.filteredEmails.push的行尝试在未初始化的数组上调用push。您的组件具有filteredEmails属性,但尚未初始化。我也不确定为什么要使用本地filteredEmails变量以及具有相同名称的类属性。

要么删除this,要么初始化属性filteredEmails: Array<any> = [];

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