首页 > 解决方案 > 从 observable 返回值以查看问题

问题描述

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

这是代码

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,但是当我将它绑定到查看时它变为空。

标签: javascriptangulardata-bindingobservablenativescript

解决方案


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

推荐阅读