angularmean-stackangular-filters

Cannot push to angular array


I have a filter to get all data from a mongoDB, to return to a table where the dates are within a selected range. However when I run the code I get an error message in the console 'Cannot read property 'push' of undefined'.

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

Solution

  • As explained by @Matt U the property is not initialized; you only assigned the type.

    So initialize it by assigning an empty array. i.e

    export class AppComponent {
      emails = [];
      filteredEmails = [];
      ...
    

    Also, when initializing with an empty array, you don't need to assign the type of property that will be done automatically.
    Good luck