I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, with bgview.component.ts being a child of single.component.ts that receives items via http requests.
Upon opening the cart component, I notice that I receive an empty array. Is there a way to store these items in the service without losing them during navigation?
I have attempted the following steps:
The component from which I want to send items:
export class BgviewComponent implements OnInit {
@Input() item: Item;
constructor(private cartservice: CartService) { }
ngOnInit() {
}
onAddToCart(){
this.cartservice.items.push(this.item);
}
}
The service :
@Injectable({
providedIn: 'root',
})
export class CartService {
public items: Item[]=[];
}
The receiving component:
export class CartComponent implements OnInit {
items: Item[]=[];
constructor(private cartservice:CartService) {
}
ngOnInit() {
this.items = this.cartservice.items;
console.log(this.items) //displays an empty array
}
}
Routing setup:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
... (contents remain unchanged from the original)
cart module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CartComponent } from './cart.component';
import .....
... (contents remain unchanged from the original)
single module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SingleComponent } from './single.component';
import .....
... (contents remain unchanged from the original)
I would greatly appreciate any assistance in resolving this issue as I seem to be stuck at the moment.