1
votes

I have two components "cart" and "home". Here "home" component is displaying list of products and it is the first page of website. I want to update cart when someone add product to the cart using "cart" button. For that I have create a service using observable to send message from "home" to "cart" component.

Problems I'm facing: 1. *ngFor is not updating when updating the array using observable. 2. As I'm initializing observable on ngOnInit() cart array is only updates when I visit cart component at least once.

home.component.ts

sendToCart(id:string) {
this.addtocart.sendId(id);
}

cart.service.ts

private productIdSource = new Subject<string>();
productId$ = this.productIdSource.asObservable(); 

constructor() { }

sendId(id:string) {
this.productIdSource.next(id);
}

cart.component.ts

itemList:any = ["hello"];

constructor(private addtocart: CartService) {
}
ngOnInit() {
  this.addtocart.productId$.subscribe(
    msg => {
      console.log(msg);
      this.itemList.push(msg);
      console.log(this.itemList);
    }
  )
}

cart.component.html

<ul>
<li *ngFor="let item of itemList">
    {{item}}
</li>
</ul>

I tried "ChangeDetectorRef", markForCheck() and detectChanges() but none of those worked.

2
Can you share it in stackbiltz - Adrita Sharma

2 Answers

0
votes

Use BehaviorSubject:

private productIdSource = new BehaviorSubject<string>();
productId$ = this.productIdSource.asObservable(); 

constructor() { }

sendId(id:string) {
   this.productIdSource.next(id);
}
0
votes

Try overwriting itemList instead of mutating:

this.addtocart.productId$.subscribe(
    msg => {
      this.itemList = [...this.itemList, msg]; // instead of this.itemList.push(msg);
    }
  )