[英]Angular load file.json and convert to object class
My app load a file.json of users'pc: 我的应用程序加载了用户PC的file.json:
app.component.html app.component.html
<div class="file btn btn-lg btn-primary"> Upload <input type="file" class="upload" (change)="changeListener($event.target.files)"> </div>
In my app.component.ts 在我的app.component.ts中
user: User;
userArray: Array<User>;
fileList: Array<any>;
ngOnInit() {
this.user = new User();
this.userArray= Array<User>();
this.fileList= Array<any>();
}
THEN the method that receive file: 然后接收文件的方法:
public changeListener(files: FileList) {
if (files && files.length > 0) {
let file: File = files.item(0);
let reader: FileReader = new FileReader();
reader.readAsText(file);
reader.onload = (e) => {
let loadFile: string = reader.result;
JSON.stringify(loadFile)
this.fileList = loadFile.split('\r\n');
if (this.fileList.length > 0) {
for (const i of this.fileList) {
if (i !== null) {
this.user = i; //--I THINK HERE IS MY PROBLEM--
this.userArray.push(this.user); //----HERE IS UNDEFINED
console.log('user - ', this.user);
} else {
console.log('NULL');
}
}
console.log('userArray - ', this.userArray.length); //---BUT HERE SHOW SIZE OF .JSON LOADED
}
}
}
My question is: Like to convert 'i' in User object? 我的问题是: 想要在User对象中转换“ i”? Or fileList in user Array?
还是用户数组中的fileList?
my user.class have same properties of json.file...I see a lot responses here but nothing works. 我的user.class具有与json.file相同的属性...我在这里看到很多响应,但没有任何效果。
My json file is a list of: 我的json文件是以下内容的列表:
{"DATE ":"22/04/2018","HOUR ":"03:00:55","YEAR ":2014,"NUM_TURN (*) ":1,"DESC_E (*) ":"Gerais 2014","SIGLA_UF ":"SE","SIGLA_UE (*) ":"SE", ...e more others 15 properties}
Aren't you using fileList
instead of this.fileList
? 您不是使用
fileList
而不是this.fileList
吗?
Anyway I would try to cast i
: 无论如何,我会尝试抛弃
i
:
this.user = i as User;
fileList
是一个字符串数组,因此您需要将i
(这是字符串类型,尽管在这种情况下为any
)转换为json对象:
this.user = JSON.parse(i);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.