【发布时间】:2021-05-03 07:12:22
【问题描述】:
我正在使用 Angular 开发 Web 应用程序的前端。我对ngOnInit() 方法有疑问。这是我的 component.ts 文件:
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();
}
}
变量timesheetInfo 在控制台中正确显示新值(包括id),正如getTimesheetInfo() 方法中所询问的那样。但是,我仍然收到此错误:
ERROR TypeError: Cannot read property 'id' of undefined
at TimesheetComponent.getRows (timesheet.component.ts:73)
at TimesheetComponent.ngOnInit (timesheet.component.ts:340)
这是关于字段this.timesheetInfo.id,我在getRows() 方法中使用:该方法在ngOnInit() 方法中使用。所以看起来变量timesheetInfo 没有在ngOnInit() 方法中更新。怎么可能?
【问题讨论】:
-
你应该链接你的调用,并确保第二个调用只有在第一个调用完成时才被执行:看看这个stackoverflow.com/questions/35268482/…
-
编辑你的问题标题,这个问题与
ngOnInit()无关 -
@lucia 请更改问题的标题,这与 ngOnInit 无关
标签: angular