Search code examples
jsonangularload

angular button load local json file to fill data object


fellows, what I want to do is to use a button to load a local file and transfer the file data into a jsonObject.

the .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>

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

The problem are:

  • this.cUser does not pass the change to html
  • alter with message of "undefined"

If I load the file by giving a static path, it works,

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

but how can I do it by an import button?

Or is there other way not using File reader? Thank you very much!!


Solution

  • The issue is the context (this) object. this object should be pointing to FileReader in your case. You can use arrow function to get rid of the issue:

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