0

Need some help. I have a product catalog and shopping cart on similar page, and I want to show item in the cart when "Buy" button will be pressed. When button is pressed the item goes to localStorage and it appears in shopping cart only after F5. I think I should use Input decorater, but how to implement it? Maybe the right way is to use services and observables but I weak at angular for now to do it. Also need to remove item from cart, I shoul rewrite localstorage for that, right?

catalog

  <div class="content">
<div class="item" *ngFor="let auto of auto; let i=index">
    <div> <img src="../../assets/db/{{auto.photo}}" alt=""></div>
  <div class="text">
    <p>{{auto.name}} - {{auto.price}} руб.</p>
    <p><input type="submit" value="Купить" (click)="toCart(i)"></p></div> 
</div>

  auto: any;
cart=[];
price=[];

constructor(private service:DataService) { }

ngOnInit() {
  this.getItems();
}
getItems(){
  this.service
     .getItems()
     .subscribe(goods => {
       this.auto = goods;
     } )
}

toCart(i){
  this.cart.push(this.auto[i]);
  this.price.push(this.auto[i].price);
  localStorage.setItem("cart",JSON.stringify(this.cart));
  localStorage.setItem("price",JSON.stringify(this.price));

}

cart component

export class CartComponent implements OnInit {
list = localStorage.getItem("cart");
names = JSON.parse(this.list);
len = this.names.length;
price = this.names.price;
Message: string;   


constructor() { }

 ngOnInit() { 
 }

send(){
  this.Message = "Готово";
  localStorage.setItem('cart',JSON.stringify(""));
 }  

// remove(i){
//     let newlist = this.names.slice(this.names[i],1);
//     console.log(newlist);
//     this.len = this.names.length - 1;
//  }

}

cart template

<div class="content">
<li *ngFor="let name of names; let i=index">
  <p>{{name.name}} - {{name.price}}руб.</p>
<button (click)="remove(i)">Удалить</button> 
  <!-- <button (click)= "add(i)">Добавить </button>   -->
</li>
<p>Количество: {{len}}  </p>
{{Message}}
<p><input type="submit" value="Оформить заказ" (click)="send()"></p>

Demmy
  • 25
  • 9

1 Answers1

0

Please try moving list = localStorage.getItem("cart"); names = JSON.parse(this.list); to ngOnInit() in cart.component.

This ensures that every time cart page is loaded , the value is updated from local storage.

Jibin TJ
  • 416
  • 1
  • 4
  • 15
  • I know, but cart page placed on product page, so it's updating only once in the beginning. – Demmy Dec 08 '17 at 12:05
  • In that case, you should use Observables. It is better to have a service and define Observables in the service. Whenever the user clicks 'Buy' , a new event should be emitted and it should be listened in 'cart component' to update the value of `names`. – Jibin TJ Dec 08 '17 at 12:13