Problems accessing variables with the FileReader

0

I have declared a variable in my component and would like to access it within a onloadend of a FileRead . I show you my code.

export class AdjuntarArchivoComponent implements OnInit {

      documentosAdjuntos: FicherosAdj[] = [];

      constructor() {
      }
     ngOnInit() {.....}

      myUploader(event) {
        for (let i = 0; i < event.files.length; i++) {
          (function (file) {
            const reader = new FileReader();
            reader.onloadend = (e) => {
              this.documentosAdjuntos.push({file: file, original: false, arrayBytes: reader.result});
            }
            reader.readAsArrayBuffer(file);
          })(event.files[i]);
        }
        this.fileInput.clear();
      }
    }

This code generates an error in this line this.documentosAdjuntos.push ({file: file, original: false, arrayBytes: reader.result});

It is the following:

ERROR TypeError: Cannot read property 'documentosAdjuntos' of undefined
    at FileReader.reader.onloadend (main.bundle.js:12929)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.bundle.js:2931)
    at Object.onInvoke (vendor.bundle.js:112820)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke (polyfills.bundle.js:2930)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runGuarded (polyfills.bundle.js:2694)
    at FileReader.<anonymous> (polyfills.bundle.js:2672)
    
asked by Richard Urquiza Santiesteban 17.10.2017 в 14:52
source

1 answer

0

On the one hand you are using arrow functions to avoid losing the context of this but on the other you are using an IIFE that causes that context to be lost. You can rewrite your function in this way

myUploader(event) {
    for (let i = 0; i < event.files.length; i++) {
        // Asigna una variable en lugar de usar un IIFE
        const file = event.files[i];
        const reader = new FileReader();
        reader.onloadend = (e) => {
            this.documentosAdjuntos.push({file: file, original: false, arrayBytes: reader.result});
        }
        reader.readAsArrayBuffer(file);
    }
}

Only assign a variable to manipulate your file instead of using an IIFE and you should already have the value of this correct.

    
answered by 17.10.2017 / 15:00
source