我正在尝试从本地磁盘加载 JSON 文件并使用其中的数据填充 FabricJS Canvas 。我在从文件中获取数据时遇到问题。
这就是我到目前为止所拥有的。
app.html
<input type="file" accept=".json" id="fileInput" (change)="loadFile($event)"/>
app.ts
loadFile(event) {
const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
const files: FileList = target.files;
this.file = files[0];
const reader = new FileReader();
reader.readAsText(this.file, 'utf8');
this.canvas.loadFromJSON(this.file, this.canvas.renderAll.bind(this.canvas), function (o, object) {
console.log(o, object);
});
对于如何实现这项工作有什么想法吗?
最佳答案
FileReader 有一个异步 API。
您必须注册 onload 事件的回调才能获取数据。
loadFile(event) {
const eventObj: MSInputMethodContext = <MSInputMethodContext> event;
const target: HTMLInputElement = <HTMLInputElement> eventObj.target;
const files: FileList = target.files;
this.file = files[0];
const reader = new FileReader();
reader.readAsText(this.file, 'utf8');
reader.onload = function() {
this.canvas.loadFromJSON(reader.result, this.canvas.renderAll.bind(this.canvas), function (o, object) {
console.log(o, object);
});
}
关于javascript - 如何在 Angular 中读取 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019003/