2

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...

1 Answer 1

5

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();
            };
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.