0

I am trying to upload an image and return its src using FileReader.

fileUpload(event) {
    var fr = new FileReader();
    fr.onload = function() {
      getImgSrc(fr.result)
    }
  }

getImgSrc(src) {
  console.log(src);
}

This returns Cannot find name 'getImgSrc'

However if I do this.getImgSrc(fr.result) I receive error getImgSrc does not exist on type'MSBaseReader' of course because the context of this. How do I access the method getImgSrc to return my async variable?

Vincent Nguyen
  • 1,555
  • 4
  • 18
  • 33
  • fr.onload = this.getImgSrc; – baao Jun 05 '18 at 15:13
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan Jun 05 '18 at 15:26

2 Answers2

2

Try using ES6 lambda arrow syntax to preserve the context of this within the handler.

fileUpload(event) {
    var fr = new FileReader();
    fr.onload = () => this.getImgSrc(fr.result);    
  }

getImgSrc(src) {
  console.log(src);
}

Regarding nothing being logged, try targeting the result of FileReader.onload from the event passed to onload in the following way:

fileUpload(event) {
    var fr = new FileReader();
    fr.onload = (event) => this.getImgSrc(event);    
  }

getImgSrc(event) {
  console.log(event.target.result);
}

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
1

You are losing the context (this) when you use non-arrow-functions (function() { ... }.

Since getImgSrc is a method and not a function in the global scope, you have to call it with this:

fr.onload = () => this.getImgSrc(fr.result);

If onload passes you the result of the image upload, you can use:

fr.onload = result => this.getImgSrc(result);

In case you did not omit this from the code in your question, you also forgot to actually start reading the file using one of the read methods:

fr.readAsBinaryString(file)   // to get a string with bytes (0-255)
fr.readAsText(file, encoding) // to get a text string
fr.readAsDataURL(file)        // to get a DataURL
fr.readAsArrayBuffer(file)    // to get an ArrayBuffer object
Leon Adler
  • 2,993
  • 1
  • 29
  • 42