角度按钮加载本地json文件以填充数据对象
伙计们,我想做的是使用一个按钮加载一个本地文件,并将文件数据传输到一个jsonObject中 .html文件:角度按钮加载本地json文件以填充数据对象,json,angular,load,Json,Angular,Load,伙计们,我想做的是使用一个按钮加载一个本地文件,并将文件数据传输到一个jsonObject中 .html文件: <div class="uuidLableLeft"> <b>Do your want to import your previous file (.json)?</b> <input style="display: none" type="file" accept=".json" (change)="onFileLoad
<div class="uuidLableLeft"> <b>Do your want to import your previous file (.json)?</b>
<input style="display: none" type="file" accept=".json"
(change)="onFileLoad($event)" #fileinput>
<button type="button" (click)="fileinput.click()"> load </button>
</div>
...
...
<div>
<textarea class="form-control" placeholder="" [(ngModel)]="cUser.vision" ></textarea>
</div>
问题是:
- this.cUser不会将更改传递到html
- 用“未定义”消息更改
this.http.request('assets/Your_filename.json')
但是我如何通过导入按钮来实现呢
或者有没有其他方法不使用文件读取器?非常感谢 问题是上下文(此
)对象在您的情况下,此
对象应指向文件读取器
。您可以使用箭头功能来解决此问题:
cUser: any;
onFileLoad(event) {
const f = event.target.files[0];
const reader = new FileReader();
reader.onload = ((theFile) => {
return (e) => {
try {
const json = JSON.parse(e.target.result);
const resSTR = JSON.stringify(json);
this.cUser = JSON.parse(resSTR);
console.log('... uuid of cUser: ', this.cUser.id);
} catch (ex) {
alert('exception when trying to parse json = ' + ex);
}
};
})(f);
reader.readAsText(f);
}
我很高兴这有帮助。再次谢谢你!
cUser: any;
onFileLoad(event) {
const f = event.target.files[0];
const reader = new FileReader();
reader.onload = ((theFile) => {
return (e) => {
try {
const json = JSON.parse(e.target.result);
const resSTR = JSON.stringify(json);
this.cUser = JSON.parse(resSTR);
console.log('... uuid of cUser: ', this.cUser.id);
} catch (ex) {
alert('exception when trying to parse json = ' + ex);
}
};
})(f);
reader.readAsText(f);
}