0
  filePhotoValue: any = "xexe";

  sendFile(file) {

    var reader = new FileReader();

    reader.onload = function (e:any) {
      console.log(this.filePhotoValue);
    };

  }

Why filePhotoValue inside reader.onload consoles "undefined" instead of xexe? There is no compilation errors and I'd like to set some value to filePhotoValue inside reader.onload.

1 Answer 1

7

While you are inside the onload method, you loose the context of "this" that is outside the method. To fix this you have two solutions: Save the "this" context in another variable:

sendFile(file) {

    var reader = new FileReader();

    var self = this;    

    reader.onload = function (e:any) {
      console.log(self.filePhotoValue);
    };

  }

or bind the current context to the function:

sendFile(file) {

    var reader = new FileReader();

    reader.onload = function (e:any) {
      console.log(this.filePhotoValue);
    }.bind(this);

  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.