Search code examples
angularangular8behaviorsubject

Angular: Sending the value of object using replaysubject


I have a add button, on which I am executing

onAddProduct(productname,price){
    this.purchasedProduct.push(productname);
    this.totalAmount += price;
    this.matBadgeNumber++;
    this.orderInfo=new OrderInfo(this.matBadgeNumber,this.purchasedProduct,this.totalAmount);
    this.tooltip = "you have "+ this.matBadgeNumber+ " products in cart";
  }

then I clicked on buy button which executes

buyNow(){
    this.http.orderDetailEmitter.next(this.orderInfo);
  }

OrderInfo

export class OrderInfo {

  matBadgeNumber: number;
  purchasedProduct: String[];
  totalAmount : Number;

  constructor(matBadgeNumber: number, purchasedProduct: String[],totalAmount : Number ) {
      this.matBadgeNumber = matBadgeNumber;
      this.purchasedProduct = purchasedProduct;
      this.totalAmount = totalAmount;
  }
}

HttpClientService

readonly orderDetailEmitter = new ReplaySubject<OrderInfo>(1);

OrderDetailsComponent

export class OrderDetailsComponent implements OnInit {

  products;
  orderDetails;

  constructor(private http : HttpClientService) {

    this.orderDetails=this.http.orderDetailEmitter;
    console.log("this.orderDetails"+this.orderDetails);
    this.products = Object.values(this.orderDetails);
    console.log("this.products"+this.products);


   }

  ngOnInit(): void {

  }

}

but while i am printing the value of orderDetails it is giving me Object [object], after using Oject.values(this.orderDetails), it is giving me some strange values

false,,false,false,false,,,,true,1,Infinity,nextInfiniteTimeWindow(value) {
        const _events = this._events;
        _events.push(value);
        if (_events.length > this._bufferSize) {
            _events.shift();
        }
        super.next(value);
    }

all I need is to get the changed value of orderInfo object via replaysubject


Solution

  • http.orderDetailEmitter is an observable. You need to subscribe to it to obtain the values. Also seeing the OrderInfo class, I think you meant to assign the list of products (purchasedProduct property) to variable this.products instead of Object.values(this.orderDetails). Try the following

    constructor(private http : HttpClientService) {
      this.http.orderDetailEmitter.subscribe(
        details => {
          this.orderDetails = details;
          console.log("this.orderDetails"+this.orderDetails);
          this.products = this.orderDetails.purchasedProduct;
          console.log("this.products"+this.products);
        }
      );
    }