'why the cart is always empty ?? is it because im not using data from api?

cart component there is to divs one when the cart is empty and one when not when I run it its always empty!

I erased the content inside the divs when cart Empty show the div below

<div *ngIf="this.items.length == 0">
 
</div>

when cart contains items show the div below

<div *ngIf="this.items.length != 0" class="container padding-bottom-3x mb-1">
  
</div>

cart.component.ts here are all functions in cart component:




@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {


  items:item[]=[];

  total:number=0;
  public grandTotal!:number;

  clearCart(){
    this.cartService.clearCart();
    this.items = this.cartService.getItems();
  }
  remove(item:item){
    this.cartService.removeItem(item);
    this.items = this.cartService.getItems();
  }

  constructor(private cartService: CartService) {



  }

  ngOnInit(): void {
    this.cartService.getProducts().subscribe(res=>{
      this.items=res;
      this.total=this.grandTotal=this.cartService.getTotalPrice();
   })

  }

}



cart.service.ts here are all functions in cart service:


export class CartService {
 cartItems:item[]=[];
 public productList=new BehaviorSubject<any>([]);

 addToCart(item: item) {
  this.cartItems.push(item);
  this.productList.next(this.cartItems);
  this.getTotalPrice();
}
getTotalPrice():number{
  let grandTotal=0;
  this.cartItems.map((a:item)=>{
    grandTotal+= a.price;
  })
  return grandTotal;
}
getItems() {
  return this.cartItems;
}
clearCart() {
  this.cartItems = [];
  this.productList.next(this.cartItems);
  return this.cartItems;
}
getLength(){
  console.log(this.cartItems.length);
  return this.cartItems.length;
}
removeItem(item:item){
  this.cartItems.splice(this.cartItems.indexOf(item),1);

}
constructor(private http: HttpClient) { }
}

why not working?????



Solution 1:[1]

Because you call productList in the wrong way, when you declare public you can access it directly without signature like this.

  ngOnInit(): void {
    this.cartService.productList.subscribe(res => {
      this.items = res;
      this.total = this.grandTotal = this.cartService.getTotalPrice();
    });

    this.cartService.addToCart({item: 'item a'});
    this.cartService.addToCart({item: 'item b'});
    this.cartService.addToCart({item: 'item c'});
    this.cartService.addToCart({item: 'item d'});

  }

Result should be show.

 <div *ngIf="this.items.length === 4" class="container padding-bottom-3x mb-1">
   Hello I'm here
 </div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paranaaan