首页 > 解决方案 > 如何在 Angular 8 中使用来自 HTML 输入的 JSON 文件?

问题描述

在我当前的 Angular 8 项目中,我有两个 JSON 文件,它们应该连接到一个 JSON 数组。然后应该导出新文件。

谷歌搜索了很长时间后,我没有找到如何使用这两个 JSON 文件的解决方案,我通过两个 HTML 输入调用这两个文件,这样我就可以将 Angular 组件中的两个文件组合成一个 JSON 数组,其中包含来自两者的输入JSON 文件。

我当前的代码:

JsonConverterComponent.html

<div class="form-group">
   <label for="Json1">Json 1</label>
      <input [(ngModel)]="json1" type="file" id="Json1" required>
</div>
<div class="form-group">
   <label for="Json2">Json 2</label>
      <input [(ngModel)]="json2" type="file" id="Json2" required>
</div>
<button [buttonLabel]="buttonNameJson" [disableCheck]="!json1 || !json2" (click)="combineJSON()"></button>

JsonConverterComponent.TS

export class JsonConverterComponent implements OnInit {

  constructor(private http: HttpClient) { }

  ngOnInit() {
  }

  buttonNameJson = "Combine JSON";
  json1: File;
  json2: File;
  test: File;

  one = this.json1;
  two = this.json2;

  public combineJSON() {
    this.test = this.one;
    console.log(this.test);
  }
}

如果我只想调用两个导入的 JSON 文件之一的内容,我总是会收到错误“未定义”。

我必须做什么才能在 JsonConverterComponent.ts 中使用单个 JSON?

标签: javascriptarraysjsonangular

解决方案


ngModel指令不能用于inputtype file,您必须对change事件做出如下反应:

<input (change)="onFileChange($event)" type="file" id="Json1" required>

<input (change)="onFileChange($event)" type="file" id="Json2" required>

然后在 TypeScript 文件中:

onFileChange(event){
    const fileToLoad = event.target.files[0];
    const fileReader = new FileReader();
    fileReader.onload = function(fileLoadedEvent){
        const textFromFileLoaded = fileLoadedEvent.target.result;
        const json = JSON.parse(textFromFileLoaded);
        console.log(json);
    };
    fileReader.readAsText(fileToLoad, "UTF-8");
}

推荐阅读