I have a fileupload in my angular2 app, which sends the file as bytearray to a webservice. I use a file reader to create a bytearray, which has an onload-event. In this event I can't reference my uploadService using this.uploadService.
public uploadHandler(event) {
var reader = new FileReader();
reader.onload = function() {
var arrayBuffer = this.result, array = new Uint8Array(arrayBuffer), binaryString = String.fromCharCode.apply(null, array);
//this.uploadService.DoUpload(binaryString);
}
reader.readAsArrayBuffer(event.files[0]);
}
I tried to use the fat arrow, but I can't reference result anymore.
reader.onload = () => {
//this.result does not exist anymore!
var arrayBuffer = result, array = new Uint8Array(arrayBuffer), binaryString = String.fromCharCode.apply(null, array);
this.uploadService.DoUpload(binaryString);
}
onloadpasses an event object as an argument, so you may check in the documentation whether you can get your "result", which seems to beevent.target.result: developer.mozilla.org/en-US/docs/Web/API/FileReader/onload . Alternatively, if you don't want to do that, you can still avoid using the fat arrows for that specific case, keeping the function declaration will effectively keep the "this" of the function declaration, hence you won't get any further problem.event.target.resulttheorically should be the same asreader.result: in your case,var arrayBuffer = this.resultis the same as writing:var arrayBuffer = reader.result, since.resultis a readonly property of the FileReader object: developer.mozilla.org/en-US/docs/Web/API/FileReader/result . So you have three ways to solve the issue, this last one is likely the fastest one.