Search code examples
angularbehaviorsubject

BehaivorSubject not keep array and duplicate


I have a service and a component, when I add a value this keeps in the array, but when I add other my first value changes the value to the second

Service

 export class PrepayService {
  private _carts: BehaviorSubject<ShoppingCart[]>; 
  carts : Observable<ShoppingCart[]>
  dataStore :{
    carts: ShoppingCart[]
  };
  constructor() { 
    this.dataStore = { carts: []};
    this._carts = <BehaviorSubject<ShoppingCart[]>>new BehaviorSubject([]);
    this.carts = this._carts.asObservable();
  }

  addData(dataObj:ShoppingCart) {
    this.dataStore.carts.push(dataObj);
    this._carts.next(Object.assign({}, this.dataStore).carts);
  }
}

Component

export class TableQuoteComponent implements OnInit {

  @Input() quote: QuoteSingle = {};
  cart: ShoppingCart;
  serviceSelected : string;

  constructor(private cartService: PrepayService) { }

  ngOnInit() {
  }
  onSubmitAdd(){
    this.cart = {};
    this.cart = this.quote;
    this.cartService.addData(this.cart);

  }
}

Second Component

export class PrePayComponent implements OnInit {
  carts: ShoppingCart[];
  constructor(private cartService: PrepayService) { }

  ngOnInit() {
    this.cartService.carts.subscribe(carts => this.carts = carts);
    console.log(this.carts);
  }

}

Array Values enter image description here enter image description here


Solution

  • In your TableQuote component, you are passing the reference of cart property in cartService.addData method, and when you add second time you change the cart property that changes the first element. You should pass copy of cart property like below

    this.cartService.addData({...this.cart});
    
    

    or

    this.cartService.addData(Object.assign({},this.cart));
    

    In javascript or typescript objects and arrays are mutable which means when you pass these variable you actually pass the reference and not just its value.