从可观察到的问题返回值

时间:2019-04-23 10:20:03

标签: javascript angular data-binding observable nativescript

我正在使用nativescript上传图像,但是无法将图像base64返回到视图进行预览,这里的问题是我的函数无法读取全局变量。 / p>

这是代码

myImg:any;
pickFiles() {
let options = {
  title: "Importer",
  cancelButtonText: "Annuler",
  actions: ["Image(s)", "Video(s)", "Audio(s)", "Fichier(s)"]
};
dialogs.action(options).then(async (result) => {
  if (result == 'Image(s)') {...}
  if (result == 'Video(s)') {...}
  if (result == 'Audio(s)') {...}
  if (result == 'Fichier(s)') {...}
  this.mdf.on("getFiles", async function (res: any) {
    let results = res.object.get('results');
    let img1 = await imageSourceModule.fromFile(results[0].file).toBase64String('jpg');
    // let img2 = await imageSourceModule.fromBase64(img1)
   this.myImg;
  });
  this.mdf.on("error", function (res) {
    let msg = res.object.get('msg');
    console.log(msg);
  });
});

我希望变量myImg获得img的新值,但是当我绑定它以查看它时,它就为空。

1 个答案:

答案 0 :(得分:0)

您从匿名函数引用的

myImg1将不会被引用,并且您必须在控制台上遇到错误。原因是匿名函数将拥有它自己的this并且不会引用组件的this。因此,您需要具有箭头功能:

您需要像这样修改代码:

pickFiles() {
let options = {
  title: "Importer",
  cancelButtonText: "Annuler",
  actions: ["Image(s)", "Video(s)", "Audio(s)", "Fichier(s)"]
};
dialogs.action(options).then(async (result) => {
  if (result == 'Image(s)') {...}
  if (result == 'Video(s)') {...}
  if (result == 'Audio(s)') {...}
  if (result == 'Fichier(s)') {...}
  this.mdf.on("getFiles", async (res: any) => {
    let results = res.object.get('results');
    let img1 = await imageSourceModule.fromFile(results[0].file).toBase64String('jpg');
    // let img2 = await imageSourceModule.fromBase64(img1)
    this.myImg = img1;
  });
  this.mdf.on("error", function (res) {
    let msg = res.object.get('msg');
    console.log(msg);
  });
});