【问题标题】:How to use JSON file from HTML input in Angular 8?如何在 Angular 8 中使用来自 HTML 输入的 JSON 文件?
【发布时间】:2020-01-06 12:41:01
【问题描述】:

在我当前的 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?

【问题讨论】:

    标签: javascript arrays json angular


    【解决方案1】:

    ngModel 指令不能用于 file 类型的 input,您必须像这样对 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");
    }
    

    【讨论】:

    • 谢谢,到目前为止工作正常,但是当我尝试连接两个 JSON 文件时,我只得到一个假路径。 C: \ fakepath \ JsonOne.jsonC: \ fakepath \ JsonTwo.json
    • “连接两个 JSON 文件”是什么意思?
    • 我想将两个JSON文件的内容转换成一个文件
    • onload 事件将在读取内容后触发,因此您转换两个 JSON 文件的逻辑应该在 onLoad 函数内。
    • 如何提取某些组件属性中的 const json?
    猜你喜欢
    • 1970-01-01
    • 2013-04-19
    • 2019-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2013-01-23
    • 1970-01-01
    相关资源
    最近更新 更多