【问题标题】:angular button load local json file to fill data object角按钮加载本地json文件以填充数据对象
【发布时间】:2018-06-27 11:45:14
【问题描述】:

各位,我要做的是用一个按钮来加载一个本地文件,并将文件数据传输到一个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')

但是如何通过导入按钮来实现呢?

或者还有其他不使用文件阅读器的方法吗?非常感谢!!

【问题讨论】:

    标签: json angular load


    【解决方案1】:

    问题在于上下文 (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);
      }
    

    【讨论】:

    • 我很高兴它有帮助。
    • 再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-11
    • 2013-08-28
    • 2012-12-07
    • 1970-01-01
    • 2021-04-10
    • 2010-12-01
    相关资源
    最近更新 更多