角形按钮加载本地json文件以填充数据对象

时间:2018-06-27 11:45:14

标签: 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($event)" #fileinput>
  <button type="button" (click)="fileinput.click()"> load </button>
 </div> 
   ...
   ...
 <div>
  <textarea class="form-control" placeholder=""  [(ngModel)]="cUser.vision" ></textarea>
</div>

.ts:

onFileLoad (event) {
  const f = event.target.files[0];
  const reader = new FileReader();

  reader.onload = (function (theFile) {
  return function (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);
}

问题是:

  • this.cUser不会将更改传递给html
  • 更改为“未定义”消息

如果我通过提供静态路径加载文件,则可以正常工作

 this.http.request('assets/Your_filename.json')

但是如何通过导入按钮来做到这一点?

还是没有其他方法不使用文件阅读器?非常感谢你!

1 个答案:

答案 0 :(得分:0)

问题是上下文(this)对象。在您的情况下,this对象应指向FileReader。您可以使用箭头功能摆脱该问题:

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