javascript - 如何在 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?
解决方案
该ngModel
指令不能用于input
type 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");
}
推荐阅读
- javascript - 正在更改的对象的属性,即使它们应该由 Value 传递
- c - 关于使用 Direct IO 进行内存对齐
- javascript - 如何在keycloak中为用户设置授权
- azure - 定期执行 ETL 时,何时使用 azure 函数与 azure 持久函数
- html - 如何使用这些 Json 数据创建 HTML 表?
- php - 拉出所有类别并按父 ID 分组
- javascript - DOM元素出现时如何跳出循环?
- java - Sonarqube 自定义 Java 插件:传感器初始化时出现不满意的依赖错误
- driverless-ai - 无人驾驶AI Python客户端
- r - 自上次活动以来经过的代码天数