file.onload 中的 Typescript 变量未定义

Typescript variable inside file.onload is undefined

  filePhotoValue: any = "xexe";

  sendFile(file) {

    var reader = new FileReader();

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

  }

为什么 reader.onload 控制台 "undefined" 而不是 xexe 中的 filePhotoValue?没有编译错误,我想将一些值设置为 filePhotoValue inside reader.onload.

当您在 onload 方法内部时,您失去了方法外部的 "this" 上下文。要解决此问题,您有两种解决方案: 将 "this" 上下文保存在另一个变量中:

sendFile(file) {

    var reader = new FileReader();

    var self = this;    

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

  }

或将当前上下文绑定到函数:

sendFile(file) {

    var reader = new FileReader();

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

  }