【发布时间】:2018-02-11 08:31:38
【问题描述】:
我的 TS 类中有一个字段:currentMonth: Month; 和 ngOnInit() 方法,它们发出 GET 请求并初始化该字段:
ngOnInit() {
this.dataService.getAllMonth(this.currentYear).subscribe(data => {
// setting current month
this.currentMonth = data.find(function (m) {
return m.numberInYear === currentDate.getMonth() + 1;
});
获得当前月份后,我想为其生成天数并显示其中的一些天数。我通过以下方式做到这一点:
1) 调用ngOnInit()中的方法
this.generateDaysForCurrentMonth(this.currentMonth);
2) 方法:
private generateDaysForCurrentMonth(mon: Month) {
let days = new Array<Day>();
for(var i = 0; i < mon.numberOfDays; i++) {
days[i] = new Day(i, mon.name, mon.year);
}
this.currentMonth.days = days;
}
3) 方法,返回ndays:
private getPartOfMonth(from: number, to: number): Array<Day>{
return this.currentMonth.days.slice(from, to);
}
4) 显示例如 7 天:
<div *ngFor="let day of getPartOfMonth(0, 7)">
<td >{{day.numberInMonth}}</td>
</div>
当我转到页面时,出现错误:ERROR TypeError: Cannot read property 'days' of undefined
在这一行:
return this.currentMonth.days.slice(from, to);
这里发生了类似的事情:
<div *ngFor="let m of months" >
<button (click)="loadMonth(m.name)" mat-raised-button >{{month.name}}</button>
</div>
month.name - 显示正确,但在方法中传递“未定义”
这段代码有什么问题?
【问题讨论】:
标签: angular typescript promise angular-promise angular5