2016-02-29 99 views
1

在Ionic 2中,<img>的src沒有在插件的回調中更新。

模板:Ionic 2:src from img not updating

<img [src]="avatar_path" id="myimg" /> 

相機使用的插件,我有以下幾點:

navigator.camera.getPicture(imageBase64 => { 
    this.avatar_path = 'data:image/png;base64,' + imageBase64; 
}, 
error => { 
    console.log(error) 
}, { 
    sourceType: Camera.PictureSourceType.PHOTOLIBRARY, 
    destinationType: 0, 
    allowEdit:true, 
    sourceType: 2 
}) 

沒有任何反應。如果我設置src用普通的js它的工作原理:

document.getElementById("myimg").src = 'data:image/png;base64,' + imageBase64; 

,如果我設置avatar_path回調外,它的工作原理。

this.avatar_path = 'data:image/png;base64,someharcodedbase64data'; 

看起來這個視圖在回調裏面沒有更新。在Ionic 1中,我會嘗試重新渲染處理$ scope或類似的東西,但我不知道Ionic 2的最佳做法。

回答

2

您需要在NgZone中運行this.avatar_path = 'data:image/png;base64,' + imageBase64;

試試下面的代碼:

import {NgZone} from 'angular2/core'; 
... 
constructor(_zone: NgZone) { 
    this._zone = _zone; 
} 
... 
navigator.camera.getPicture(imageBase64 => { 
this._zone.run(() => { 
    this.avatar_path = 'data:image/png;base64,' + imageBase64;  
}); 
} 
+2

你能解釋一下爲什麼嗎? :S – Eusthace

+0

如果我也在指令中? :S – Eusthace

+1

任何解釋都不錯。對我的問題沒用。 – StinkyCat