Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 + Typescript + FileReader.onLoad = property does not exist

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,

like image 950
da45 Avatar asked Jan 19 '17 09:01

da45


2 Answers

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

like image 147
Günter Zöchbauer Avatar answered Oct 19 '22 04:10

Günter Zöchbauer


You are using a regular javascript function here:

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

The this belongs to the function not your class.

Use arrow function

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

Or

self = this;
 reader.onload = function(e) {
        self.text=reader.result;
     }
like image 4
Suraj Rao Avatar answered Oct 19 '22 05:10

Suraj Rao