html – Accessing variable inside fileReader onload function in ts-ThrowExceptions

Exception or error:

I have been trying to upload image from reading base64 path using file reader.
first, i used a code like,

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

here, all the variables declared inside onload using “this” didn’t get updated outside. but when i changed the code like,

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

it worked perfectly as expected. I couldn’t catch up what is the mistake on the first code and why second code works fine. I would like anyone to help me with understanding this…

How to solve:

It’s scope issue.

you can use an arrow function (() => {}) Like below to keep this in scope

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

Leave a Reply

Your email address will not be published. Required fields are marked *