2017-09-02 333 views
1

我想從本地磁盤加載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://stackoverflow.com/questions/16930473/angularjs-factory-http-get-json-file) – user93

回答

0

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