Ionic 2:来自 img 的 src 未更新

Ionic 2: src from img not updating

在 Ionic 2 中,来自 <img> 的 src 不会在插件的回调内部更新。

模板:

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

没有任何反应。如果我用纯 js 设置 src,它就可以工作:

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

如果我在回调之外设置 avatar_path,它会起作用。

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

似乎视图没有在回调中更新。在 Ionic 1 中,我会尝试重新渲染它来处理 $scope 或类似的东西,但我不知道 Ionic 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;      
});
}