I am currently trying to define an array of objects in my Typescript code. However, I am encountering issues when accessing these objects. Below is the snippet of my code along with a screenshot showing the output of this.attachments
.
info: Info[];
if (this.attachments.length > 0) {
this.previewInfo(this.attachments);
}
previewInfo(infos) {
this.info = [];
for (let i = 0; i < infos.length; i++) {
let reader = new FileReader();
reader.onload = (e: any) => {
var temp = new Info;
temp = {
id: i,
url: e.target.result,
message: ""
}
this.info.push(temp);
}
reader.readAsDataURL(infos[i]);
}
}
The resulting output displays an empty array at the beginning as follows.
[]0: {id: 0, url: "test1", message: ""}
1: {id: 1, url: "test2", message: ""}
2: {id: 2, url: "test3", message: ""}
This leads to undefined errors when attempting to retrieve them using
this.info[0]
If I exclude the second line which resets this.info=[]
, I encounter an error message that says
Cannot read property '0' of undefined
Is there an issue with how I declared it? How can I effectively access info by its index?