2017-02-09 22 views
0

這是一個後續:ngOnChange not storing previousValue propertyangular2 SimpleChange沒有存儲`previousValue`

我使用ionic2/angular2與此組件:https://github.com/crisbeto/angular-svg-round-progressbar和使用ChromeDevTools以下標記

<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> 

,我在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。但如果是這樣,簡單的解決方法是什麼?

+0

我的猜測是正確的。如果我使用Object.assign(snapshot,o.toJSON())',那麼'snapshot'引用* same *對象,'SimpleChange.previousValue'正確保存'snapshot.remaining'的前一個值。但是,那麼我有可能得到'檢查出錯後,表達已經改變'。解決辦法是什麼? – michael

回答

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()我得到相同屬性o.snapshot與更新的屬性值和SimpleChange正確存儲changes.current.previousValue