угловая кнопка загрузки локального файла JSON для заполнения объекта данных - PullRequest
0 голосов
/ 27 июня 2018

ребята, я хочу использовать кнопку для загрузки локального файла и передачи данных файла в 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
  • изменить с сообщением "undefined"

Если я загружаю файл с помощью статического пути, он работает,

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

а как мне сделать это кнопкой импорта?

Или есть другой способ не использовать File Reader? Большое спасибо !!

1 Ответ

0 голосов
/ 27 июня 2018

Проблема в объекте контекста (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);
  }
...