The problem I'm facing revolves around the Typescript aspect of an Angular application.
I am dealing with a data array that I receive from a subscription. It consists of multiple objects with "titleName" and "ID" properties, but their number is neither consistent nor predictable. I need to include a "toggle" property for interaction within the component. However, due to constraints related to the database call and its various other uses, adding "toggle" on the service side is not a viable option. I have attempted the following:
titlesraw;
titles: any;
...
getTitles() {
this.getTitles.subscribe(
data => {
this.titlesraw = data;
console.log(this.titlesraw); //the console output is as expected
for (var i = 0; i < this.titlesraw.length; i++) {
let title = {
id: this.titlesraw[i]["ID"];
titleName: this.titlesraw[i]["titleName"];
toggle: true;
}
console.log(title); //the console shows the expected values
this.titles.push(title);
}
}
)
}
However, upon running the code, I encounter the following error:
ERROR TypeError: Cannot read properties of undefined (reading 'push') at <line with this.titles.push(title)>
I believe this error stems from a incorrect declaration of titles
. What changes should I make to rectify this issue?
EDIT: I modified titles: any;
to titles: any[] = [];
, but now I face a new error:
Cannot read properties of undefined (reading 'ID') at <line with this.titles.push(title)>.
Despite this, when I print out the temporary variable title
, it displays exactly what I expect.