How can I prevent a component in Angular 5 from triggering its subscription twice when the component is placed twice inside another component? For example, I have a NavMenuComponent with two instances of a cart in its template.
<!-- cart 1 in nav fixed -->
<nav-menu-cart class="toolbar-item" *ngIf="auth.isAuthenticated()"></nav-menu-cart>
<!-- cart 2 in nav scrolled -->
<nav-menu-cart class="toolbar-item" *ngIf="auth.isAuthenticated()"></nav-menu-cart>
Within the NavMenuCartComponent, there is a subscription in the constructor:
this.subscription = cartConnectorService.cartItemAdded$.subscribe(
newCartItem => {
console.log("in cartConnectorService.cartItemAdded$.subscribe");
this.saveCartWithNewItem(newCartItem);
});
The saveCartWithNewItem function gets called twice instead of once (as evidenced by the log screenshot below).
https://i.sstatic.net/FYAlb.pngYou might wonder why the NavMenuCartComponent handles the call to saveCartWithNewItem instead of having the data managed within a CartService and just refreshing the data in the NavMenuCartComponent. The reason is that the CartService only deals with HTTP calls, not data storage at the moment.
The ProductsGridComponent, which makes use of the CartConnectorService, is the original component responsible for triggering the Observable.
I aim to allow the ProductsGridComponent to add items to the cart while ensuring that both instances of NavMenuCartComponent receive the updated data and persist it through the service. Although I used the CartConnectorService for this purpose, I now encounter the issue of duplicate invocation. Any assistance would be appreciated.