2016-02-29 96 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