Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
角度按钮加载本地json文件以填充数据对象_Json_Angular_Load - Fatal编程技术网

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

角度按钮加载本地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

伙计们,我想做的是使用一个按钮加载一个本地文件,并将文件数据传输到一个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>
问题是:

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