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

时间:2019-07-02 15:20:52

标签: angular typescript angular7 angular-components

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);
    }
  }

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

  

无法读取未定义的属性“ id”

请参考第console.log("LOADED " + this.attivita.id);行,紧接在我之后:

enter image description here

似乎抓住了两倍的变化。但是,这两个变化是什么?在本教程中,对此一无所知。我如何处理而不会出现错误?

1 个答案:

答案 0 :(得分:2)

您需要检查currentValue是否存在。

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