Home > Mobile >  Angular 14 get data from unrelated component
Angular 14 get data from unrelated component

Time:01-19

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 :)

CodePudding user response:

Use BehaviorSubject. It is the simplest way in angular to share data between unrelated component.

https://www.infragistics.com/community/blogs/b/infragistics/posts/simplest-way-to-share-data-between-two-unrelated-components-in-angular

https://medium.com/codex/how-to-share-data-between-components-in-angular-a-shopping-cart-example-b86ce8254965

CodePudding user response:

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

  • Related