【问题标题】:html trying to access fields before promise finishes [duplicate]html试图在承诺完成之前访问字段[重复]
【发布时间】: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


    【解决方案1】:

    使用安全导航运算符。 {{currentMonth?.name}}。当 currentMonth 为 null 或 undefined 时尝试访问 currentMonth 属性时,它将返回 null 并且不会抛出错误。

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 2019-06-13
      • 2015-07-18
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      相关资源
      最近更新 更多