weinde
weinde

Reputation: 1156

Angular 14 get data from unrelated component

I need help with understanding data sharing between components... I have a project that has a cart page and a footer that is a standalone component and is included in every page of my app... In the footer I have a cart icon and on that icon I'm trying to show the number of items in cart... I get the data of items in cart from an API... Do I have to call this api and all of its data in the footer component with the same function as in the cart page also or is there a shorter simpler way that uses less code?

In the image bellow you can see this footer component (NOTE: 11 is hardcoded at the moment): enter image description here

Here is the the API response how the cart data looks like:

{
    "total_products": 0,
    "totals": null,
    "notes": null,
    "shipping_method": null,
    "products": []
}

Here is the code of cart.page.ts that I use to show data in my app:

  ngOnInit() {
    this.getCart();
  }

  getCart() {
    this.getCartSubscription = this.cartService.getCart().subscribe(
      (data: any) => {
        const productsData = data.body.products;
        const totalProducts = data.body.total_products;
        const totalCartPrice = data.body.totals;
        this.products = productsData.map(products => products);
        this.totalProducts = totalProducts;
        this.totalCartPrice = totalCartPrice;
        console.log('Products in cart:', data.body);
      },
      error => {
        console.log('Error', error);
      });
  }

How do I approach to showing total products in my footer component?

Is my code even good? Is there a way to optimize it? This is my first real Angular project and I would like to do this as propperly as possible :)

**EDIT: I have read about and tried using BehaviourSubject but am unsure of it implementation in my case...

Thank you very much :)

Upvotes: 0

Views: 197

Answers (2)

Bart Barnard
Bart Barnard

Reputation: 1168

You could decorate the page-component with @Output and the footer with @Input. See this page on angular.io

I've created a simple example you can find on StackBlitz. However, I think as your application grows it will be better just to use a service the call the backend (as you are doing in your cart-component) and have all interested component subscibe to it.

Upvotes: 2

Related Questions