简体   繁体   English

如何在Angular中读取JSON文件?

[英]How do I read a JSON file in Angular?

I am trying to load a JSON file from local disk and use the data from it to fill a FabricJS canvas. 我正在尝试从本地磁盘加载JSON文件,并使用其中的数据来填充FabricJS画布。 I have problems on getting the data from the file. 我从文件中获取数据时遇到问题。

This is what i have till now. 这就是我到目前为止所拥有的。

app.html 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);
});

Any thoughts on how I can make this work? 关于如何进行这项工作有任何想法吗?

FileReader has an async api. FileReader具有异步api。

You must register a callback to the onload event to get the data. 您必须注册一个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);
});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM