我有以下组件加载文件并将其内容绑定为字符串
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"]);
}
}
问题是this.csvChange
内部未定义onLoadCallback
那么我如何将结果传递给组件中的某个变量呢?
我正在搜索其他类似的question https://stackoverflow.com/questions/30830268/how-to-make-filereader-work-with-angular2但永远不会在 onloadCallback 函数之外得到结果
问题在于,当您执行以下操作时,上下文会丢失:
reader.onload = this.onLoadCallback;
一种解决方案是:
reader.onload = (e: Event) => {
this.onLoadCallback(e);
}
另一种是:
reader.onload = this.onLoadCallback.bind(this);
还有一个是:
onLoadCallback = (event) => {
this.csvChange.emit((event.target as FileReader).result);
}
底线。确保this
上下文始终保留在您的内部class
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)