I am working on the frontend of a Web app with Angular. I have an issue with the ngOnInit()
method. This is my component.ts file:
export class TimesheetComponent implements OnInit {
timesheetInfo: ITimesheetInfo;
month: number;
year: number;
employeeEmail: string;
dataSource: ITimesheetRow[] = [];
constructor(private translate: TranslateService, private notify: NotificationService, private timesheetService: TimesheetService) {}
getTimesheetInfo(employeeEmail: string, month: number, year: number): void {
this.timesheetService.getTimesheetInfo(employeeEmail, month, year).subscribe({
next: (data): void => {
this.timesheetInfo = data;
console.log(this.timesheetInfo);
},
error: (err): void => {
if(err.status != 401) {
this.notify.error(this.translate.instant('ERRORS.GENERAL_ERROR'))
}
}
});
}
getRows(): void {
this.timesheetService.getCurrentRows(this.timesheetInfo.id).subscribe({
next: (data): void => {
this.dataSource = data;
},
error: (err): void => {
if (err.status != 401) {
this.notify.error(this.translate.instant('ERRORS.GENERAL_ERROR'));
}
}
});
}
ngOnInit(): void {
this.employeeEmail = 'mymail@gmail.com';
this.month = 1;
this.year = 2021;
this.getTimesheetInfo(this.employeeEmail, this.month, this.year);
this.getRows();
}
}
The variable timesheetInfo
is displayed correctly with the new values (including the id) in the console, as asked inside the getTimesheetInfo()
method. However, I still get this error:
ERROR TypeError: Cannot read property 'id' of undefined
at TimesheetComponent.getRows (timesheet.component.ts:73)
at TimesheetComponent.ngOnInit (timesheet.component.ts:340)
This is about the field this.timesheetInfo.id
, which I use in the getRows()
method: this method is used inside the ngOnInit()
method. So it seems that the variable timesheetInfo
isn't updated inside the ngOnInit()
method. How is it possible?