【发布时间】: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