【问题标题】:Accessing variable inside fileReader onload function in ts在ts中访问fileReader onload函数中的变量
【发布时间】:2020-02-22 07:49:30
【问题描述】:

我一直在尝试使用文件阅读器从读取 base64 路径上传图像。 首先,我使用了类似的代码,

const reader: FileReader = new FileReader();
            reader.onload = function(e: any) {
                const imgBase64Path = e.target.result;
                this.documentBase64 = imgBase64Path;
                this.isImageSaved = true;
                this.documents.content = imgBase64Path.toString();
            };

在这里,使用“this”在 onload 中声明的所有变量都没有在外部更新。但是当我更改代码时,

const reader: FileReader = new FileReader();
            const this_ = this;
            reader.onload = function(e: any) {
                const imgBase64Path = e.target.result;
                this_.documentBase64 = imgBase64Path;
                this_.isImageSaved = true;
                this_.documents.content = imgBase64Path.toString();
            };

它按预期完美运行。我无法理解第一个代码的错误是什么以及为什么第二个代码可以正常工作。我希望有人能帮助我理解这一点...

【问题讨论】:

    标签: html angular typescript filereader


    【解决方案1】:

    这是范围问题。

    您可以使用箭头函数(() => {}) 如下所示将其保持在范围内

    const reader: FileReader = new FileReader();
                reader.onload = (e: any) => {
                    const imgBase64Path = e.target.result;
                    this.documentBase64 = imgBase64Path;
                    this.isImageSaved = true;
                    this.documents.content = imgBase64Path.toString();
                };
    

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 2018-12-02
      • 2018-06-06
      • 1970-01-01
      相关资源
      最近更新 更多