In my service, I am populating an array of items by calling a function like this:
items: IItem[] = [];
...
LoadItems() {
this.GetItems().subscribe((res) => {
// console.log(res);
if (res.status == 200 && res.body.data != undefined) {
var data = res.body.data;
this.items.push({
Id: data[i].id,
IsBlue: data[i].isBlue, //this is a bool
});
}
}
// console.log(this.items.length);
});
}
This function is called within the ngOnInIt method in my app.component.ts file. Afterwards, I want to filter out and work with only the blue items in the array in item.component.ts like so:
GetBlueItems(items: IItem[]) {
var blueitems: IItem[] = [];
console.log(items); //this returns the array correctly
for (let i = 0; i < items.length; i++) {
if (items[i].isBlue) {
blueitems.push(items[i]);
}
}
However, the loop is not iterating through the array. When I check the length of the array using console.log(items.length)
, it returns 0, even though console.log(items)
shows that the array is not empty.
I have attempted to use a forEach loop as well, but it also fails to iterate through the array:
items.forEach(item => {
if (item.isBlue) {
blueitems.push(item);
}
});
I would like to be able to access and use this array outside of the subscription block. I do not need the array to be continuously updated. The array is needed for displaying information in the HTML, as well as various functions within the application such as managing a shopping cart and checkout process.
Edit: I want to utilize the array outside the subscription block for the purpose of displaying information in HTML, as well as using it for tasks like adding items to a shopping cart and completing transactions. It seems challenging to effectively utilize the array if I am restricted to using it only within the subscription block.