首页 文章

如何将数据从parrent构造函数传递给角度为2的子组件

提问于
浏览
1

我有一个有角度的2页,我需要使用来自外部API的相同数据数组显示2个不同的组件 . Parent是常规组件,子项在使用相同功能的其他几个组件之间共享 .

在父组件类中,我声明了输出属性:

public weatherList: WeatherForecast[];
@Output() public weatherListData: any;

在父组件的内部构造函数中,我使用来自外部API的数据填充 weatherListData 属性

http.get(url)
        .subscribe(result => {
            this.weatherList= result.json() as WeatherForecast[];
            this.weatherListData = this.weatherList;
        });

我在父模板中成功使用它,如: {{ weatherList.someValue }}

此外,在父组件模板中,我有一个子组件的调用

<daily-temperature-chart [weatherListData]='weatherListData'></daily-temperature-chart>

在子组件类中,我声明了属性

@Input() weatherListData: any;

但是,当我尝试在构造函数或子组件的init中访问 weatherListData 属性时,我得到未定义的结果 .

EDIT :我玩过console.log()并注意到子组件Constructor和OnInit()方法在父组件的http.get()之前返回 . 也许这是问题,但我告诉你 .

有人能指点我怎么解决这个问题吗?

1 回答

  • 1

    你需要构造函数或OnInit,因为组件初始化不依赖于你的服务调用这种情况,只要你的输入值被更新OnChanges就会提供 OnChanges .

    ngOnChanges(changes: any){
      console.log(changes);
      console.log(this.weatherListData);
     }
    

    OnChanges也传递一个参数,该参数通知当前状态和过去状态,现在您可以使用输入值 . 如果您的组件基于输入,输入基于任何其他操作,您可以在此块中处理它 .

相关问题