I made an Angular Service that keeps a list of items that other components can add items to and can retrieve. For some reason nothing gets added to the list. It does only within the add() function of my service but the variable doesn't get changed outside of it.. For example, at the end of the add() function, the console returns the item that was added. But when I check the list again from the getItems() function list is empty. Why would list doesn't get updated outside of the function after push?
export class BasketService {
private list: Item[] = [];
constructor() {}
add(product: Product, units: number): void {
let item: Item = new Item();
item.product = product;
item.units = units;
this.list.push(item);
console.log(this.list[(this.list.length - 1)]);
// Log shows item object
}
getItems(): Observable<Item[]> {
console.log(this.list);
// Log shows empty array
return of(this.list);
}
}
EDIT
getItems() does have a subscriber however the issue doesn't seem to come from there since it receives an empty array of Item, the same empty list that is printed by the console in getItems (in the basketService).
export class BasketComponent implements OnInit {
items: Item[];
constructor(private basketService: BasketService) {}
ngOnInit() {
this.getItems();
console.log(this.items.length);
}
getItems(): void {
this.basketService.getItems()
.subscribe(items => {
this.items = items; });
}
getItems?