【问题标题】:ngOnChange not storing previousValue propertyngOnChange 不存储 previousValue 属性
【发布时间】:2016-11-14 01:12:07
【问题描述】:

[Angular2 @ RC4] [angularfire2 @ 2.0.0-beta.2]

在我的子组件中,我无法让 changes['posX'].previousValue 存储任何内容。

来自父 html 的片段:

//inside *ngfor loop
[posX]='coord.position_x | calculateX:395'
[posY]='coord.position_y | calculateY:380'

子组件的片段:

export class childComponent implements OnChanges {
  @Input() posX: number; //updated via firebase database from parant
  @Input() posY: number; //updated via firebase database from parant

  ngOnChanges(changes: {[ propName: string]: SimpleChange}) {
    console.log('Change detected: ', changes['posX'].currentValue);
    console.log('Change detected: ', changes['posX'].previousValue);
  }

来自 chrome 控制台的结果:

Change detected: posX current =  343 //changes every time
Change detected: posX previous = Object {} //same after updates

我发现了这个 plnkr 的 ngOnChange 并且能够让它在我的应用程序中运行。虽然我无法让 PosX 和 PosY 变量以相同的方式工作。

变量 PosX 和 PosY 每 15 秒通过我的 firebase 数据库中的 observable 更新一次。知道为什么 previousValue 没有出现吗?

【问题讨论】:

  • 我可以通过changes['myProp'].previousValue在控制台中看到以前的值
  • 对不起,我将编辑我的问题以更好地澄清它。我可以让 plnkr 正常工作,也可以从从事我项目的 plunker 那里获取示例,但由于某种原因,我的 PosX / PosY 变量的更新与示例中的 change 变量不同。
  • “PosX / PosY 变量的更新与示例中的更改变量不同。”是什么意思。 currentValue 到底应该是什么?

标签: typescript angular firebase angularfire2


【解决方案1】:

我能找到的最佳答案是 OnChanges() 无法检测到坐标的更改,因为它是对坐标对象的引用,而不是实际值。

直接引用:

hero 属性的值是对 hero 对象的引用。 Angular 并不关心英雄自己的 name 属性是否发生了变化。 hero 对象引用没有改变,所以从 Angular 的角度来看,没有需要报告的变化!

链接:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges

【讨论】:

    猜你喜欢
    • 2017-06-27
    • 1970-01-01
    • 2019-04-04
    • 2015-09-16
    • 2022-01-14
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    相关资源
    最近更新 更多