Greeshma Nimmala
Greeshma Nimmala

Reputation: 61

Unable to send the data between components in Angular

I am working on a project where there is 'Add to Cart' button which display the quantity and total amount for all the products. I am able to view the cart total when used inside the shopping component. But when am trying to have a separate component for 'cart'am unable to view the items that I have added into the cart.There is a problem with component communication.

cart.component.ts

cartItems=[];

cartTotal=0;


  constructor(private messageService:MessangerService) { }

  ngOnInit(){
    this.messageService.getMessage().subscribe((product:Product)=>{
      // console.log(product);
      this.addProductToCart(product)
    })
  }

  addProductToCart(product:Product){

    let productExist=false;

    for(let i in this.cartItems){
      if(this.cartItems[i].productId === product._id){
        this.cartItems[i].qty++
        productExist=true;
        break;
      }
    }

    if(!productExist){

      this.cartItems.push(
        {
          productName:product.name,
          qty:1,
          price:product.price,
          productId:product._id
        }

      );

    }

    this.cartTotal=0;
    this.cartItems.forEach(item=>{
      this.cartTotal+=(item.qty*item.price)
    });

  }

cartItem.component.ts

Input() cartItem:any

cartItem.component.html

<div class="cart-item">
    <span>{{cartItem.productName}}</span>*<span>{{cartItem.qty}}:</span> <strong>{{cartItem.qty*cartItem.price| currency:'CAD'}}</strong>
</div>

cart.component.html

<div  *ngIf="cartItems.length ===0" class="alert alert-info">
    No Items
</div>

<ul *ngIf="cartItems.length>0" class="list-group">
    <li class="list-group-item" *ngFor="let item of cartItems">
        <app-cart-item [cartItem]="item"></app-cart-item>
    </li>
    <li class="list-group-item active">
        <strong>Total</strong>{{ cartTotal|currency:'CAD'}}
    </li>
</ul>

cart-page.component.html

//This doesn't display my products that have been added into the cart page

But when I am enclosing my 'cart' in shopping component it displays the list of items I have added.

<div class="container">
    <div class="row">
        <div class="col-md-10">
            <app-product-list></app-product-list>
        </div>
        <div class="col">
        <app-cart></app-cart>
        </div>
    </div>
</div>

routing.module.ts

{
    path:'cart',component:CartPageComponent
  }

My folder Hierarchy: enter image description here

Upvotes: 0

Views: 141

Answers (1)

CouchCode
CouchCode

Reputation: 305

The best way I have found to do this is the use of rxjs BehaviorSubjects. When you update the BehaviorSubject, every component that subscribes to it will be updated.

I would create a cart service something like this

@Injectable()
export class CartService {
    private cart = new BehaviorSubject<Array<Product>>([]);
    public cart$ = this.cart.asObservable();

    public addItemToCart(product: Product): void {
        let cartArr = [...this.cart.value];
        cartArr.push(product)
        this.cart.next(cartArr)
    }
}

then subscribe to the cart$ observable in the constructor of every component you need the cart data for

public cartContents: Array<Product>;
constructor(private readonly cartService: CartService){
    this.cartService.cart$.subscribe(x => this.cartContents = x)
}

Upvotes: 1

Related Questions