can’t iterate over array created in service – async issue?

  Kiến thức lập trình

I create an array of Items like this in my service:

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 is called in ngOnInIt in my app.component.ts file. Then I want to iterate over this array of Items like so in item.component.ts:

GetBlueItems(items: IItem[]) {
    var blueitems: IItem[] = [];
    console.log(items); //this returns the array correctly

    for (let i = 0; i < items.length; i++) {
        if (item.isBlue) {
            blueitems.push(item);  
        }
    }

But it just never iterates over the array. When I do console.log(items.length) it returns 0, which confuses me because console.log(items) shows that the array is not empty.

I’ve tried printing the length of the array within the subscribe block and it does return the length correctly, so I assume it’s an issue with synchronization? But then I still don’t understand why the console would print this without issue:

0: {Id: 1, IsBlue: false }
1: {Id: 2, IsBlue: true }
length: 2

I’ve also tried doing a forEach loop over the array, but it won’t iterate with that either:

items.forEach(item => {
    if (item.isBlue) {
        blueitems.push(item);  
    }
});

I would like to be able to use this array outside of the subscribe block if that even is the issue. I don’t need it to be updated constantly.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT