angular - 无法推送到角度数组
问题描述
我有一个过滤器可以从 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);
}
}
解决方案
您调用的行this.filteredEmails.push
试图调用push
未初始化的数组。您的组件有一个filteredEmails
属性,但它没有被初始化。我也不确定为什么你有一个局部filteredEmails
变量以及一个同名的类属性。
要么删除this
,要么初始化属性filteredEmails: Array<any> = [];
如果你打算使用组件类的属性,你只需要初始化那个变量。如果您打算仅使用filteredEmails
方法中声明的变量,请删除this
.
推荐阅读
- vue.js - 为什么 Vue 在这种情况下不响应?
- python - 如果没有任何改变,如何避免建造新车轮
- python - 为什么 lxml 不允许在整个 ElementTree 上使用相对 XPath 表达式?
- powershell - 通过 bat 文件运行 powershell 命令时出现问题
- html - Rich Link Preview 不适用于 Whatsapp IOS 但适用于 Android
- android - 如何在活动之间导航时将服务绑定到多个活动而不停止?
- c# - 在 ASP.NET MVC 中使用 ajax 将数据从视图传递到控制器
- docker - 詹金斯“Docker 构建和发布”插件不起作用
- java - 在 VSCode 的 Microsoft Debugger for Java 扩展中,是否可以让它知道 Lombok?
- angular - 有条件地在 Angular Http 拦截器中设置标题