I have an injectable service that retrieves shopping cart items:
@Injectable({
providedIn: 'root'
})
export class CartService {
private readonly items: Array<{ product: IProduct, quantity: number }>
private subject = new Subject<Array<{ product: IProduct, quantity: number }>>()
constructor() {
this.items = []
}
getItems() {
return this.subject
}
addItem(product: { product: IProduct, quantity: number }) {
const isProductExists = this.items.find((item => item.product._id === product.product._id))
if (isProductExists) {
isProductExists.quantity += product.quantity
} else {
this.items.push(product)
}
this.subject.next(this.items)
}
}
In my CartComponent
i subscribe to items
and iterate them in an *ngFor
:
export class CartComponent implements OnInit {
myItems: { product: IProduct, quantity: number }[]
constructor(private cartService: CartService) {
}
ngOnInit(): void {
this.cartService.getItems().subscribe(items => {
this.myItems = items
})
}
}
Here is the template:
<div *ngFor="let item of myItems">{{item.product.name + ', ' + item.product.price }}</div>
The thing is that nothing is displayed on the page, even though the subscribe method is invoked
and I can clearly see that myItems
is updating.
what I do wrong in this code?