从Angular 2中的FileReader获取值 [英] get the value from a FileReader in Angular 2
本文介绍了从Angular 2中的FileReader获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下组件,该组件可加载文件并将其内容绑定为字符串
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"]);
}
}
问题是this.csvChange
在onLoadCallback
内部未定义,因此如何将结果传递给组件中的某个变量?
the problem is that this.csvChange
is undefined inside onLoadCallback
so how I could pass the result to some variable in my component?
我在搜索其他类似的问题,但从未得到结果在onloadCallback函数之外
I was search other similar question but never get the result outside of onloadCallback function
推荐答案
问题是执行此操作时上下文会丢失:
The problem is that the context is lost when you do:
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
内部.
Bottom line. Make sure that the this
context always remains inside your class
.
这篇关于从Angular 2中的FileReader获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文