1

I am wondering how to properly refresh the data in the component if there is any update. In my main panel I have a cart tab which displays the current number of products in the cart This is retrieved using endpoint from the backend

My navigation-cart component:

@Component({
  selector: 'navigation-cart',
  templateUrl: './navigation-cart.component.html',
  styleUrls: ['./navigation-cart.component.scss']
})
export class NavigationCartComponent extends implements OnInit {


  private cartItemCount$: Observable<Number>;

  public cartItemsCount: number;

  constructor(
    public eventbus: EventBusService,
    public cartService: CartService
    ) {
    this.eventbus.on('refreshCartCount', (state: any) => {
      console.log('maybe i should refresh here')

    });
  }
  ngOnInit() {
    this.cartItemCount$ = this.cartService.cartItemCount();
    this.cartItemCount$.subscribe(cartCount => {
      console.log(cartCount['productsCount'])
      this.cartItemsCount = cartCount['productsCount']
    }
    )
  }
}

property cartItemsCount is current number of items in cart from backend.

cartService:

@Injectable({
  providedIn: 'root'
})
export class CartService {
 

  public cartItemCount(): Observable<Number> {
    console.log('cartItemCount')
    return this.http.get<any>(`http://localhost:8000/basket/count`);
  }

}

If I add a product to the cart in another component how do I update the number of items in the cart?

  1. When adding a product to the cart should I emit an event that I catch in my component? How this emit should look like?

  2. Using Ngrx to store the current status of the cart:

ngOnInit(){    
store.dispatch(new cartCount());
}

and every update update this value

I'm just getting started with angular. How should it be done properly?

jrywin
  • 147
  • 1
  • 11

1 Answers1

1

On first page load you can get it from API service, but after that you have to subscribe from Subject to get alert for how many items are added.

You should pass an object with all the information about the product being added.

cartService.ItemAdded$.next(item)
vaira
  • 2,191
  • 1
  • 10
  • 15
  • Could you give me more information? After im adding product to basket i'm thinking about sending new request to backend to get current product quantity – jrywin Nov 18 '21 at 19:29
  • 1
    I see you are using ngrx, there are methods to take a slice of store from the listner component and in the source component you can update the value using actions – Deepak Jha Nov 18 '21 at 19:39
  • 1
    you are sending it in the backend to store it, but your cart notification does not keep an open connection and does not need to when you can just use a common service between product and Notification Center to update it. – vaira Nov 18 '21 at 20:30
  • So it's better use ngrx to this or service class connecting two Component? – jrywin Nov 18 '21 at 21:18
  • 1
    Both will work , I prefer Rxjs since its easier to read and backtrack. – vaira Nov 18 '21 at 21:27