如何在Angular中读取JSON文件?

问题描述:

我想从本地磁盘加载JSON文件,并使用它的数据填充FabricJS画布。我在从文件中获取数据时遇到问题。如何在Angular中读取JSON文件?

这是我到现在为止。

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); 
}); 

上我怎样才能使这项工作有什么想法?

+0

为什么只是不使用一个服务至极加载一个$ http json文件。 –

+0

[AngularJS:factory $ http.get JSON文件]的可能重复(https://*.com/questions/16930473/angularjs-factory-http-get-json-file) – user93

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); 
}); 
}