Karl Karl - 3 years ago 129
TypeScript Question

Can't reference this in typescript

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);
}

Answer Source

the fat arrow is the right way to go. and you can also get the result from the reader variable instead of this. so it could look like this

public uploadHandler(event) {
    var reader = new FileReader();
    reader.onload = () => {
        var arrayBuffer = reader.result;
        var array = new Uint8Array(arrayBuffer);
        var binaryString = String.fromCharCode.apply(null, array);
        this.uploadService.DoUpload(binaryString);
    };
    reader.readAsArrayBuffer(event.files[0]);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download