【问题标题】:angular2 SimpleChange is not storing `previousValue`angular2 SimpleChange 不存储“previousValue”
【发布时间】:2017-06-27 07:57:51
【问题描述】:

这是对ngOnChange not storing previousValue property的后续跟进

我将ionic2/angular2 与此组件一起使用:https://github.com/crisbeto/angular-svg-round-progressbar 和以下标记

<ion-card  class="timer"
  *ngFor="let snapshot of timers | toJSON"
> 
  <ion-card-content>
    <round-progress 
      [current]="snapshot.remaining" 
      [max]="snapshot.duration"
      [rounded]="true"
      [responsive]="true"
      [duration]="18"
      >
    </round-progress>
</ion-card>

使用 ChromeDevTools,我在 SimpleChange.current 中看到以下内容:

  /** Change detection callback. */
  ngOnChanges(changes): void {
    if (changes.current) {
      this._animateChange(changes.current.previousValue, changes.current.currentValue);
    } else {
      this._setPath(this.current);
    }
  }
// changes.current.previousValue = {}
// changes.current.cureentValue = 123 // int
// changes.current.isFirstChange() = true

为什么我没有正确存储changes.current.previousValue

toJSON 管道调用此方法,该方法返回一个匿名对象:

  /**
   * create a snapshot of the timer
   */
  toJSON() : TimerAttributes {
    const remaining = this.check(true);
    console.log(this.id, this.duration, remaining)
    return {
      id: this.id,
      label: this.label,
      // asMilliseconds
      duration: this.duration,
      // asMilliseconds
      remaining: remaining,
      humanize: this.humanize(remaining),
      // as Unixtime
      expires: this.expires
    }
  } 

我唯一的猜测是我在每个更改检测循环中为snapshot 返回一个不同的对象,所以我丢失了previousValue。但如果是这样,那么简单的解决方法是什么?

【问题讨论】:

  • 我的猜测是正确的。如果我使用Object.assign(snapshot, o.toJSON()),那么snapshot 引用same 对象,SimpleChange.previousValue 正确保存了snapshot.remaining 的previousValue。但是,那么我就有可能遇到Expression has changed after it was checked 错误。解决办法是什么?

标签: angular


【解决方案1】:

SimpleChange 不存储 previousValue 的正确值,如果 @Input 变量的对象发生变化。

  /**
   * create a snapshot of the timer, return as anonymous object
   */
  toJSON() : TimerAttributes {
    const remaining = this.check();
    // console.log(this.id, this.duration, remaining)
    return {
      id: this.id,
      label: this.label,
      // asMilliseconds
      duration: this.duration,
      // asMilliseconds
      remaining: remaining,
      humanize: this.humanize(remaining),
      // as Unixtime
      expires: this.expires
    }
  }


  /**
   * return the SAME object with updated attr value 
   */
  snap(): TimerAttributes {
    Object.assign( this.snapshot, this.toJSON())
    return this.snapshot;
  }

如果我的toJSONPipe 调用o.toJSON(),我会得到一个带有属性值的匿名 对象,而SimpleChange 不存储changes.current.previousValue

如果我的 toJSONPipe 调用 o.snap(),我会得到 SAME 属性 o.snapshot 更新后的属性值和 SimpleChange 正确存储 changes.current.previousValue

【讨论】:

    猜你喜欢
    • 2016-11-14
    • 2016-02-03
    • 2022-01-18
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多