angular2 SimpleChange不存储`previousValue`

时间:2017-02-09 10:41:17

标签: angular

这是对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。但如果是这样,那么简单的解决办法是什么?

1 个答案:

答案 0 :(得分: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