【问题标题】:ngOnInit() method not working as expectedngOnInit() 方法没有按预期工作
【发布时间】: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


【解决方案1】:

推荐的实现方式是使用 rxjs 操作符, 你可以这样做。

    getTimesheetInfo(employeeEmail: string, month: number, year: number): void {
    this.timesheetService.getTimesheetInfo(employeeEmail, month, year)
      .pipe
      (
        tap(timeSheetInfo => {
          this.timesheetInfo = timeSheetInfo;
        }),
        switchMap(() => {
          return this.timesheetService.getCurrentRows(this.timesheetInfo.id);
        }),
        tap(data => {
          this.dataSource = data;
        }),
        catchError(err => {
          if (err.status != 401) {
            this.notify.error(this.translate.instant('ERRORS.GENERAL_ERROR'));
          }
          return EMPTY;
        })
      )
      .subscribe();
  }

【讨论】:

    【解决方案2】:

    当您调用 getRows() 时,this.timesheetInfo 的值尚未设置

    你应该要么使用asyncawait,要么在getTimesheetInfo()的回调函数中调用你的getRows()方法

        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);
    
              // here, after you set this.timesheetInfo
              this.getRows();
    
            },
            error: (err): void => {
              if(err.status != 401) {
                this.notify.error(this.translate.instant('ERRORS.GENERAL_ERROR'))
              }
            }
          });
        }
    

    【讨论】:

    • 我不想让您与 async/await 混淆,但考虑学习它们,因为它们是更好、更易读的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    相关资源
    最近更新 更多