TypeScript图片上传,fileReader.onload异步无法赋值给全局变量


1、无法传值给全局变量

protected getImage(image: any) {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(image.files[0]);
    // tslint:disable-next-line:typedef
    fileReader.onload=function() {
  // 这里是无法赋值给base64Url的
      this.base64Url = fileReader.result;
    }
  }
2、怎样才能赋值呢?需要将函数改成箭头形式
protected getImage(image: any) {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(image.files[0]);
    // tslint:disable-next-line:typedef
   // 这种才可以给全局变量赋值
    fileReader.onload = ()=> {
      this.base64Url = fileReader.result;
    }
  }
 
// 将文件读取为base64,并将数据保存在result中
fileReader.readAsDataURL(image.files[0]);
 
页面代码:

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM