get the value from a FileReader in Angular 2

梦想的初衷 提交于 2019-12-24 04:53:34

问题


I have the following component that load a file and bind his content as string

    export class NgCsvComponent {

        @Input() csv: any;

        @Output() csvChange: any = new EventEmitter();

        public localCsv : any = '';

      constructor() { }

      changeListener($event): void {
        this.readFile($event.target);
      }

      readFile (inputValue : any) : void {
        let reader = new FileReader (),
              file : File = inputValue.files[0];
          reader.readAsText(file);    
        reader.onload = this.onLoadCallback;
      }

        onLoadCallback (event) {
            this.csvChange.emit(event.target["result"]);
        }
    }

the problem is that this.csvChange is undefined inside onLoadCallback so how I could pass the result to some variable in my component?

I was search other similar question but never get the result outside of onloadCallback function


回答1:


The problem is that the context is lost when you do:

reader.onload = this.onLoadCallback;

One solution is:

reader.onload = (e: Event) => {
    this.onLoadCallback(e);
}

Another one is:

reader.onload = this.onLoadCallback.bind(this);

Yet another one is:

onLoadCallback = (event) => {
    this.csvChange.emit((event.target as FileReader).result);
}

Bottom line. Make sure that the this context always remains inside your class.



来源:https://stackoverflow.com/questions/39979809/get-the-value-from-a-filereader-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!