首页 > 解决方案 > 无法推送到角度数组

问题描述

我有一个过滤器可以从 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);
    }
}

标签: angularmean-stackangular-filters

解决方案


您调用的行this.filteredEmails.push试图调用push未初始化的数组。您的组件有一个filteredEmails属性,但它没有被初始化。我也不确定为什么你有一个局部filteredEmails变量以及一个同名的类属性。

要么删除this,要么初始化属性filteredEmails: Array<any> = [];如果你打算使用组件类的属性,你只需要初始化那个变量。如果您打算仅使用filteredEmails方法中声明的变量,请删除this.


推荐阅读