0

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")
      }
    )
  }
}
1
  • What exactly do you have problem with? I can't understand what you are asking for. Commented Nov 18, 2021 at 18:39

1 Answer 1

0

The issue is that you are using a subject, instead of a BehaviourSubject.

You cart component only starts subscribing when it is created (when you go to the cart page), by that time you have already pushed the item in product component and the events done before reaching cart are lost, you can avoid this by using BehaviourSubject as it will give you the last pushed value by the product.

private _cartData = new BehaviorSubject<Item[]>([]);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.