There're two components. One has products and on click each product push in empty array (addedToCart) in this component. Then using service and subject, from cart component I subscribe this array(addedToCart). But product start pushing after I go to cart page (using routing) and back to the product page.
product component
export class ProductComponent implements OnInit {
productList: Item[] = [];
addedToCart: Item[] = [];
constructor(private data: DataService, private cartDataServise:CartDataService) { }
addToCart(product:Item){
this.addedToCart.push(product)
this.cartDataServise.sendCartData(this.addedToCart)
}
service
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class CartDataService {
private _cartData = new Subject<any>();
myCartData$ = this._cartData.asObservable()
constructor() { }
sendCartData(cartData:any){
this._cartData.next(cartData);
}
}
cart component
export class CartComponent implements OnInit {
cartItems:Item[] = [];
constructor(private cartDataService:CartDataService) { }
ngOnInit(): void {
this.cartDataService.myCartData$
.subscribe(
cartData => {
this.cartItems = cartData
console.log(this.cartItems)
console.log("vaxo")
}
)
}
}