使用 ngOnChanges 将异步数据传递给子组件不起作用

Pass async data to child component with ngOnChanges does not work

根据 this tutorial,正是解决方案 n 2,我尝试以这种方式将异步数据传递给子组件:

父组件 ts :

ngOnInit() {
    this.route.queryParams.subscribe(params => { 
   this.networkService.getAttivitaById(this.idAttivita).subscribe((att:Attivita[]) => {
          this.attivita = att[0];
        })
  }

父组件html:

<app-dettaglio-attivita [attivita]="attivita" [isModifica]="isModifica" [intervento]="intervento"></app-dettaglio-attivita>

然后是子组件:

@Input() attivita: Attivita;
[...]

ngOnChanges(changes: SimpleChanges) {
    if(changes['attivita']){
      this.initPage();
      console.log("LOADED " + this.attivita.id);
    }
  }

当我转到该页面时,在控制台中按顺序打印:

cannot read property 'id' of undefined

指的是行 console.log("LOADED " + this.attivita.id); 之后我有:

好像赶上了两倍的变化。但这两个变化是什么?在教程中没有关于此的字样。我怎样才能在没有错误的情况下处理这个问题?

您需要检查 currentValue 是否存在。

ngOnChanges(changes: SimpleChanges) {
    const { attivita } = changes;
    if (attivita && attivita.currentValue) {
      this.initPage();
      console.log("LOADED " + this.attivita.id);
    }
}