Angular2 + Typescript + FileReader.onLoad =属性不存在 [英] Angular2 + Typescript + FileReader.onLoad = property does not exist

查看:583
本文介绍了Angular2 + Typescript + FileReader.onLoad =属性不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FileReader接口并使用异步方法 readAsText()来读取本地文本文件,
之后 onload事件被调用,我尝试读取我的文件,我的源代码如下:

  export class ReadFileComponent {
text:string;

readFile():void {
let reader = new FileReader();
reader.onload = function(e){
this.text = reader.result;
}
reader.readAsText(file);
}
}

编译失败,因为Property text 类型FileReader b

我认为这是由于EventListener接口不接受对象, p>

有人请解决这类问题吗?



谢谢你们,

解决方案

如果你想在回调中使用这个,请使用箭头功能,否则它将无效

  reader.onload =(e)=> {
this.text = reader.result;
}

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions


I am using the FileReader Interface and it’s asynchronous method readAsText() to read a local text file, After that when the onload event is called, I try to read my file, my source code is something like the following:

export class ReadFileComponent {
   text: string;

   readFile(): void {
     let reader=new FileReader();
     reader.onload = function(e) {
        this.text=reader.result;
     }
     reader.readAsText(file);   
   }
}

compilation is failed because Property "text" does not exist on type "FileReader"

I think this is due to the EventListener interface does not accept objects ,

did someone please solve this kind of issue?

thanks guys,

解决方案

If you want to use this inside the callback, use an arrow function, otherwise it won't work

reader.onload = (e) => {
    this.text=reader.result;
}

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

这篇关于Angular2 + Typescript + FileReader.onLoad =属性不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆