0

I have a field in my TS class: currentMonth: Month; and ngOnInit() method, which make a GET request and initialize this field:

ngOnInit() {
  this.dataService.getAllMonth(this.currentYear).subscribe(data => {

  // setting current month
  this.currentMonth = data.find(function (m) {
    return m.numberInYear === currentDate.getMonth() + 1;
  });

After getting a current month, I want to generate days for it and display some of them. I do this with following:

1) calling a method in ngOnInit()

this.generateDaysForCurrentMonth(this.currentMonth);

2) The method:

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) method, which returns n days:

private getPartOfMonth(from: number, to: number): Array<Day>{
 return this.currentMonth.days.slice(from, to);
}

4) displaying for example 7 days:

<div *ngFor="let day of getPartOfMonth(0, 7)">
    <td >{{day.numberInMonth}}</td>
</div>

when I go to page, I got an error: ERROR TypeError: Cannot read property 'days' of undefined

In this line:

return this.currentMonth.days.slice(from, to);

something similar happens here:

<div *ngFor="let m of months" >
  <button (click)="loadMonth(m.name)" mat-raised-button >{{month.name}}</button>
</div>

month.name - displays correct, but in method it pass "undefined"

What is the problem for this code?

Illia
  • 45
  • 6

1 Answers1

0

Use safe navigation operator. {{currentMonth?.name}}. It will return null and not throw error when trying to access currentMonth properties when currentMonth is null or undefined.

Roberto Zvjerković
  • 9,657
  • 4
  • 26
  • 47