首页 > 解决方案 > 如何从父组件刷新我的数据?

问题描述

嗨,我想从父组件刷新我的时间戳值。

我的 parentComponent.ts

public updateComponent(){
    this.timestamp = new Date();
    this.timestamp.setDate(this.timestamp.getDate() - 30);
    this.timestamp = this.timestamp.toJSON();
}

public ngOnInit() {
  this.updateComponent();
  interval(10000).subscribe(() => {
      console.error('called');
      console.error(this.timestamp);
      this.updateComponent();
  });

}

//my parent.component.html
<app-dashboard-card [refresh]="timestamp"></app-dashboard-card>



//When I catch my data
private ts: any;

@Input()
set refresh(timestamp: any) {
  console.error("TIMESTAMP CHANGE -> ", timestamp);
  this.ts = timestamp;
};

我不知道为什么我的@Input 在时间戳更改时没有捕捉到。

标签: angular

解决方案


您的代码似乎在这里工作只是使用setInterval().

建议:这里不用setter也可以达到同样的效果只需在您的子组件中获取您的时间戳,如下所示 -

@Input() timestamp: any;

ngOnChanges() {
    console.log("TIMESTAMP CHANGE -> ", this.timestamp);
}

注意:记得检查控制台的日志。


推荐阅读