【问题标题】:return value from observable to view problem从 observable 返回值以查看问题
【发布时间】:2019-04-23 10:20:02
【问题描述】:

我正在使用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 的新值,但是当我将它绑定到查看时它变为空。

【问题讨论】:

  • this.myImg; 您希望这如何分配新值?.. this.myImg = img1; 可能是您正在寻找的。此外,删除 function 并将其替换为 lambda,否则 this 将被限定。
  • 是的,但他没有把它作为一个全局变量,当我用 ctrl 单击它时它不会返回到全局变量( vs 代码),当我试图给它一个简单的构造函数中的字符串并在此函数中更改它不会更改
  • 如果它没有分配它,它的this 是不正确的,因为包裹在一个function 块中。能否请您展示更多可使用的代码?
  • export class NvPubComponent implements OnInit { type; objectif; submitted; myImg; mdf = new Mediafilepicker(); pickFiles(){ } 那是我的课
  • 好的,所以只需将 async function (res: any) 替换为:(res: any)(将其转换为 lambda)并将 this.myImg 分配给 img1。使用 lambda,其中的 this 将是类的 this(在这种情况下,组件的 this)

标签: javascript angular data-binding observable nativescript


【解决方案1】:

您从匿名函数引用的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);
  });
});

【讨论】:

  • 它是这样的,但它也不起作用,这很奇怪,即使当我点击 this.myImg 时也不会返回到全局变量
  • 放一个控制台并尝试打印 myImg 你看到了什么?
  • 它打印它但是当我用其他函数再次调用它时它显示为空
猜你喜欢
  • 1970-01-01
  • 2021-09-24
  • 2015-01-11
  • 2021-11-14
  • 1970-01-01
  • 2021-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多