Reputation: 4000
I'm trying to read a file and store the read content in a private variable of Component. So far, I cannot access properties of components, as I get referral for this
as FileReader
not component.
My code is like this
private ReadTheFile(file:File) {
var myReader: FileReader = new FileReader();
myReader.readAsText(file);
myReader.onloadend = function (e) {
//Do something here with myReader.result
}
//Get the modified result here, and assign it to public property.
}
So, how to access Component properties inside a method like this? Which is method of FileReader
instance, not Component.
Upvotes: 1
Views: 796
Reputation: 71911
Don't use the keyword function
inside a class. This will change the this
context as you've noticed. use the arrow function
private ReadTheFile(file:File) {
var myReader: FileReader = new FileReader();
myReader.readAsText(file);
myReader.onloadend = (e) => {
//Do something here with myReader.result
}
//Get the modified result here, and assign it to public property.
}
Upvotes: 4
Reputation: 6674
You can use an arrow function to preserve component context:
myReader.onloadend = (e) => {
//Do something here with myReader.result
}
Upvotes: 1