html - 访问 ts 中 fileReader onload 函数内的变量

标签 html angular typescript filereader

我一直在尝试使用文件阅读器从读取 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();
            };

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

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

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

最佳答案

这是范围问题。

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

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

关于html - 访问 ts 中 fileReader onload 函数内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60350130/

相关文章:

html - 使用直接的 HTML 标签而不是 div.class

angular - 将Angular CLI项目与Groovy Gradle App集成

html - 输入标签中的#id 是什么意思?

typescript :函数声明中接口(interface)属性的类型安全

reactjs - 如何防止(卸载)TypeScript 安装并将它自己的 @types 引用到 AppData\Local

javascript - 如何使用 JavaScript 进行表单验证?

html - 限制对特定 div 的关注

javascript - 在某些属性中按部分搜索数组部分

html - 位置 :fixed navigation header overlapping browser scroll bar when using overflow-x

html - 模板解析错误